简体   繁体   中英

PHP: check if image exists (methods)

I have more than 5000 image links and I need to find a way to check if they exist. I used getimagesize() , but it took too long. The speed is critical for me.

I wrote a little function, but it's not working, I don't know why.

function img_exists($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if(curl_exec($ch))
        return true;
    else
        return false;

    curl_close($ch);
}

At the moment I am performing the check with PHP. Please let me know if there is any better solution.

Notice that if the connection is times out (1 sec) then the function returns false. The speed is critical.

UPDATE: Files are located on a different server.

If you can, curl_multi_* functions should make the whole process faster, check the manual .

Also, just doing an HEAD request (instead of GET ) will save you quite some bytes / time, add this:

curl_setopt_array($ch, array(CURLOPT_HEADER => true, CURLOPT_NOBODY => true));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD');

if you have to chek files on your own server, you can simply use file_exists() - if you need to check remote files and have allow_url_fopen enabled, you could use fopen() like this:

function url_exists($path){
    return (@fopen($path,"r")==true);
}

a little note to your function: you're trying to call curl_close() after returning a value, so this statement is senseless as it will never be reached (and may cause memory-leaks because you're never closing the stream).

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