简体   繁体   中英

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 (ie 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?

file_exists()然后使用getimagesize()检查文件是否真的是图像

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;
}

How about this

if(filesize($url))
{
}

That way, you are not triggering GD operations..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM