I have this script where I fetch image links from specific websites, therefore I created a function where I pass the image link and source name of the website which will be used for placing the images on their corresponding directories.
However sometimes this function wouldn't work properly, randomly it would save the image however the image is basically empty, thus it would just save an empty file with the original filename from the $img_link, but fails to show the actual image.
In that case if that happens I tried to return me a default image path. But it fails to do so and returns an empty image as explained above.
function saveIMG($img_link, $source){
$name = basename($img_link); // gets basename of the file image.jpg
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_" .$name;
if (!empty($img_link)){
$ch = curl_init($img_link);
$fp = fopen("images/$source/$name", 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_HEADER, 0);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
$name ="images/$source/$name";
return $name;
}
else {
$name = "images/news_default.jpg";
return $name;
}
}
Do you have any better idea, how to make a case when it fails to get retrieve an image?
Thanks
file_get_content
is always a good alternative to cURL.
But, if you want/have to use cURL:
$ch = curl_init("www.path.com/to/image.jpg");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); //Return the transfer so it can be saved to a variable
$result = curl_exec($ch); //Save the transfer to a variable
if($result === FALSE){//curl_exec will return false on failure even with returntransfer on
//return? die? redirect? your choice.
}
$fp = fopen("name.jpg", 'w'); //Create the empty image. Extension does matter.
fwrite($fp, $result); //Write said contents to the above created file
fclose($fp); //Properly close the file
And that's it. Tested it and it works.