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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
paladaxar
Forum Commoner
Posts: 85
Joined: Fri Jun 18, 2004 11:50 pm

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

Post 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?
Last edited by paladaxar on Wed Aug 23, 2006 3:32 pm, edited 1 time in total.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

fopen() maybe?
paladaxar
Forum Commoner
Posts: 85
Joined: Fri Jun 18, 2004 11:50 pm

Post 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.
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post 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.
paladaxar
Forum Commoner
Posts: 85
Joined: Fri Jun 18, 2004 11:50 pm

Post 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.
Post Reply