Handle error when getimagesize can't find a file

Viewed 40941

when I'm trying to getimagesize($img) and the image doesn't exist, I get an error. I don't want to first check whether the file exists, just handle the error.

I'm not sure how try catch works, but I want to do something like:

try: getimagesize($img) $works = true
catch: $works = flase
5 Answers

This solution has worked for me.

try {
    if (url_exists ($photoUrl) && is_array (getimagesize ($photoUrl)))
    {
        return $photoUrl;
    }
} catch (\Exception $e) { return ''; }

Simple and working solution based on other answers:

$img_url = "not-existing.jpg";

if ( is_file($img_url) && is_array($img_size = getimagesize($img_url)) ) {
  print_r($img_size);
  echo "OK";
} else {
  echo "NOT OK";
}
Related