views:

620

answers:

2

Hi, when I'm trying to getimagesize($img) and the image dos't exist I get an error. I don't wont to first check if the file exist, just handle the error.

I'm not sure how try-catch works, but I wont to do like:

try: getimagesize($img) $works = true
catch: $works = flase
+2  A: 

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 to 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 ;-)
Pascal MARTIN
Mind you, if file_exists() tells the file exists, getimagesize() may still fail, as the file may be deleted just in between method calls. Veeery unlikely, but happens in worst moments...
ya23
@ya23 : true ; but you'd have to be very unlucky ^^ And I don't like masking errors with @ : if you are using it, and have a problem, it's generally quickly a pain to debug :-(
Pascal MARTIN
A: 

Call me a dirty hacker zombie who will be going to hell, but I usually get around this problem by catching the warning output into an output buffer, and then checking the buffer. Try this:

ob_start();
$data = getimagesize('not-existing.png');
$resize_warning = ob_get_clean();
if(!empty($resize_warning)) {
  print "NOT OK";
  # We could even print out the warning here, just as PHP would do
  print "$resize_warning";
} else {
  print "OK"
}

Like I said, not the way to get a cozy place in programmer's heaven, but when it comes to dysfunctional error handling, a man has to do what a man has to do.

Rude