com*_*ude 2 php curl image save-image
我有这个脚本,我从特定网站获取图像链接,因此我创建了一个功能,我传递图像链接和网站的源名称将用于将图像放在相应的目录上.
但是有时这个函数不能正常工作,随机它会保存图像,但图像基本上是空的,因此它只会保存一个空文件,其中包含来自$ img_link的原始文件名,但无法显示实际图像.
在这种情况下,如果发生这种情况,我试图返回一个默认的图像路径.但它没有这样做并返回如上所述的空图像.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
你有什么更好的想法,当它无法检索图像时如何制作案例?
谢谢
file_get_content 总是cURL的一个很好的替代品.
但是,如果你想/必须使用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
Run Code Online (Sandbox Code Playgroud)
就是这样.测试它,它的工作原理.