Page 1 of 1

[solved] check if an image file exists before getting info

Posted: Wed Aug 23, 2006 2:39 pm
by paladaxar
I have a site that links to external images. When someone specifies the url where their image is, I tried to use getimagesize() or exif_imagetype() to determine whether it is a valid image or not. Well, if the file exits, these functions do a great job at determining file types (albiet VERY slowly [sometimes over 1.5 seconds]). But, if the user gives me a url that doesnt even exist, both of the aforementioned functions produce errors. Error shown here:

Warning: exif_imagetype(http://www.lalala.com/images/foo.jpg) [function.exif-imagetype]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found in...yada yada

Is there a function that will check if the url even exists before I run imagesize on it?

Posted: Wed Aug 23, 2006 2:45 pm
by Luke
fopen() maybe?

Posted: Wed Aug 23, 2006 2:55 pm
by paladaxar
Thanks ninja. I think that might work, but looking into the function led me to find another that I think was created for just this purpose: file_exists(). It seems to be working well.

Posted: Wed Aug 23, 2006 2:58 pm
by Ollie Saunders
but looking into the function led me to find another
There you go the power of the PHP manual is indeed great. file_exists() is a good choice.

Posted: Wed Aug 23, 2006 3:31 pm
by paladaxar
Haha...yeah...the manual is pretty amazing ;) I was just so burned out at the time I was trying to figure this out that I couldnt even think of what to search for.

But, file_exits() actually DOESNT work for what I am trying to do. I posted to quickly without fully testing.

On the page that talks about file_exists(), someone (leibwaechter at web dot de) posted this helpful peice of code:

Code: Select all

<?php
function url_exists($url)
{
 $handle = @fopen($url, "r");
 if ($handle === false)
  return false;
 fclose($handle);
 return true;
}
?>
I tested a few more times before posting this time. I think its finally working.