Wednesday, 18 September 2013

Broken images after download using php curl

Broken images after download using php curl

I have a class that allows me to download images using php curl. My class
looks like this:
function getImage($img, $path) {
$fullpath = basename($img);
$ch = curl_init($img);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$rawData = curl_exec($ch);
curl_close($ch);
if(file_exists($fullpath)) {
unlink($fullpath);
}
$fp = fopen($path.$fullpath, "w+");
fwrite($fp, $rawData);
fclose($fp);
}
This works okay for most images but there are also instances in which I
get broken images instead. I've tried checking the path of the image from
the website and it's correct. My question is, why is this happening and
how can I prevent images being downloaded broken?

No comments:

Post a Comment