palmaceous
palmaceous

Reputation: 41

PHP: Check if a file exists on a server

Hey; I'm currently using the following way of checking whether an image exists on a server:

if (@getimagesize($s3url))
   { 
      //do stuff 
   }

Needless to say, that's hardly the most elegant way of doing that... But honestly, I don't actually know where to start looking for a better solution.

I was wondering if perhaps it was possible to just send a request, receive a HTTP response (i.e. if the HTTP response is 200, carry on, if not, evaluate to false); but is that the best way?

What is the best function to check for the existence of an (image) file?

Upvotes: 0

Views: 2558

Answers (3)

Ryan Pendleton
Ryan Pendleton

Reputation: 2626

I'm not sure if file_exists works for remote urls, so you'de be safer to use this:

function url_exists($url) {
    $handle   = curl_init($url);

    curl_setopt($handle, CURLOPT_HEADER, false);
    curl_setopt($handle, CURLOPT_FAILONERROR, true);
    curl_setopt($handle, CURLOPT_NOBODY, true);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, false);
    $connectable = curl_exec($handle);
    curl_close($handle);   
    return $connectable;
}

Upvotes: 2

arbithero
arbithero

Reputation: 436

How about this

if(filesize($url))
{
}

That way, you are not triggering GD operations..

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

file_exists() then check whether the file really is an image or not using getimagesize()

Upvotes: 4

Related Questions