I have created a function with two input parameters. 1 inputs the image url, the other one basically a string, which is the source name of the image. I have tried to created it in a such way where if it fails to get the image, return a default image path. However this works in cases if it fails to get the image, but it would not work sometimes and create basically empty image files, thus my thinking is that the image is unable to be fully downloaded.
My code is below.
function saveIMG($img_link, $source){
$name = date("Y-m-d_H_i_s_") . mt_rand(1,999) . "_".$source.".jpg";
$ch = curl_init($img_link);
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_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
if ($result === FALSE){ //curl_exec will return false on failure even with returntransfer on
$name = "images/news_default.jpg";
return $name;
}
else {
$fp = fopen("images/$source/$name", 'w');
fwrite($fp, $result);
curl_close($ch);
fclose($fp);
$name ="images/$source/$name";
return $name;
}
}
Do you have any idea how to make sure to only save working images, and not empty images, and in case if the image is empty return me a default news image.
Hope I was clear enough.
You could use getimagesize("img") and check the type.