我有这个脚本,可以从特定网站获取图像链接,因此我创建了一个函数,在该函数中我传递图像链接和网站的源名称,用于将图像放置在相应的目录中。
然而,有时这个函数无法正常工作,它会随机保存图像,但图像基本上是空的,因此它只保存一个空文件,其中包含$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;
}
}
你有什么更好的主意吗,当它无法检索到图像时,如何提出理由?
感谢
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
就是这样。测试了它,它起作用了。
使用文件获取内容
$data = file_get_contents($img_link);
//check it return data or not
if ( $data === false )
{
echo "failed";
}