Search code examples
phptry-catchgetimagesize

Handle error when getimagesize can't find a file


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

Solution

  • Like you said, if used on a non-existing file, getimagesize generates a warning :

    This code :

    if ($data = getimagesize('not-existing.png')) {
        echo "OK";
    } else {
        echo "NOT OK";
    }
    

    will get you a

    Warning: getimagesize(not-existing.png) [function.getimagesize]: 
      failed to open stream: No such file or directory 
    


    A solution would be to use the @ operator, to mask that error :

    if ($data = @getimagesize('not-existing.png')) {
        echo "OK";
    } else {
        echo "NOT OK";
    }
    

    As the file doesn't exist, $data will still be false ; but no warning will be displayed.


    Another solution would be to check if the file exists, before using getimagesize ; something like this would do :

    if (file_exists('not-existing.png') && 
        ($data = getimagesize('not-existing.png'))
       ) {
        echo "OK";
    } else {
        echo "NOT OK";
    }
    

    If the file doesn't exist, getimagesize is not called -- which means no warning

    Still, this solution is not the one you should use for images that are on another server, and accessed via HTTP (if you are in this case), as it'll mean two requests to the remote server.

    For local images, that would be quite OK, I suppose ; only problem I see is the notice generated when there is a read error not being masked.


    Finally :

    • I would allow errors to be displayed on your developpement server,
    • And would not display those on your production server -- see display_errors, about that ;-)