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
  • 26,156
  • 14
  • 79
  • 87
Jordan
  • 231
  • 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
  • 741,623
  • 53
  • 500
  • 612
  • 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
  • 2,086
  • 5
  • 23
  • 37
  • 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