Search code examples
phpcurlfile-exists

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.


Solution

  • 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');