2

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.

Michal
  • 3,262
  • 4
  • 30
  • 50
Reteras Remus
  • 923
  • 5
  • 19
  • 34
  • The images are remote or is this script being run on the same hosting space as the images? if so could just use `file_exists()` – RedactedProfile Mar 30 '12 at 21:02

2 Answers2

5

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');
Alix Axel
  • 151,645
  • 95
  • 393
  • 500
  • If you don't want to see the HEAD result, add curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); – Acyra Feb 27 '16 at 17:10
2

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).

oezi
  • 51,017
  • 10
  • 98
  • 115