tags:

views:

66

answers:

2

Morning all,

I am using CURL to download an image file within a loop. The first time it runs fine and I see the image appear in the directory.

The second time it fails with a timeout, despite it being a valid URL.

Can anyone suggest why it always fails on the 2nd time and how to fix it?

The snippet of code is:

// download image

$extension = "gif";
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 90);
curl_setopt($ch, CURLOPT_URL, $imgurl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
echo $imgurl . " attempting to open URL ";
$i = curl_exec($ch);
if ( $i==false ) {
  echo curl_errno($ch).' '.curl_error($ch);
}
$image_name=time().'.'.$extension;
$f = fopen('/fulldirectorypath/' . $image_name ,'w+');
fwrite($f,$i);
fclose($f);

I have put an echo in there to display the $IMGURL, to check it is valid, and upped the timeout to 90 secs, but it still fails. This is what I see on screen:

http://images.eu-xmedia.de/thumbnails/34555861/5676051/pt=pic,lang=2,origfile=yes/image.gif attempting to open URL 28 Operation timed out after 90 seconds with 0 bytes received

an empty file is created in my directory.

thanks alot,

Greg

A: 

If you are hitting the same site over and over, they may have something which times out requests coming in too fast. If you are looping, try adding a brief sleep after each iteration.

One thing you should probably look in to using is multi-curl. It runs Curl operations in parallel. The section on Curl Functions on php.net documents them. I'd suggest looking at this tutorial. Someone out there has probably written an object-oriented abstraction of curl and multi-curl.

Tom Morris
I've tried a 60 second sleep, but I still have the same problem...
kitenski
A: 

Try adding curl_close($ch); after fclose($f);. It seems likely to me that it is trying to reuse the connection, which is in return causing the issue.

Joseph
Thanks Joseph, I have just tried that but still see the same issue.
kitenski
If you run a single instance (instead of in a loop) and then refresh the browser as soon as it is complete, does it work then?
Joseph
Interesting...I created a small test file, with a different IMG link it works, with the one identified above I get the same issue....
kitenski
Is the new test file a gif as well?
Joseph
yes, this one failshttp://images.eu-xmedia.de/thumbnails/34555861/5676051/pt=pic,lang=2,origfile=yes/image.gifthis one workshttp://images.eu-xmedia.de/thumbnails/246380/5710261/pt=pic,lang=2,origfile=yes/image.gif
kitenski
Out of curiosity, why are you trying to download the image within a loop? If you are simply putting it in an image tag, you can put the url straight in it, and it should work.
Joseph
because I am taking lots of records from an XML file and writing them into a database, or in the case of the image, writing a link to the local file into the database. I cannot simply link to the URL :(
kitenski