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.

1
  • 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() Commented Mar 30, 2012 at 21:02

2 Answers 2

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');
Sign up to request clarification or add additional context in comments.

1 Comment

If you don't want to see the HEAD result, add curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
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).

2 Comments

Can you add a custom timeout to fopen?
@haltabush you can timeout for fsockopen

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.