0

Code:

if(isset($_POST['update_avatar'])) {
    $url = $_POST['avatar'];
    $info = getimagesize($url);

    if(isset($info['name'])) {
        echo "Exists";
    } else {
        echo "Error";
    }
}

How can I avoid getting PHP errors when the user types an invalid URL, random piece of text or invalid image URL etc?

Rikesh
  • 24,843
  • 14
  • 73
  • 84
Jordan
  • 221
  • 1
  • 12

2 Answers2

0

If there's an error, getimagesize returns false, so test for that. And to suppress error messages from a function, put @ before it:

$info = @getimagesize($url);
if (!$info) {
    echo "Error";
} else {
    // Process the image
}
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • I still get the following error either way: Warning: getimagesize(www.google.com): failed to open stream: No such file or directory in / – Jordan Mar 03 '15 at 20:01
  • You can use the `@` prefix to suppress error messages. – Barmar Mar 03 '15 at 21:14
0

Use exception handling. Place your critical code into a try..catch block. You can find more information here.

Mitulát báti
  • 1,178
  • 3
  • 15
  • 30
  • I still get the following error either way: Warning: getimagesize(www.google.com): failed to open stream: No such file or directory in / – Jordan Mar 03 '15 at 20:01