3 回答
TA贡献1824条经验 获得超5个赞
尝试这个:
function grab_image($url,$saveto){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
$raw=curl_exec($ch);
curl_close ($ch);
if(file_exists($saveto)){
unlink($saveto);
}
$fp = fopen($saveto,'x');
fwrite($fp, $raw);
fclose($fp);
}
并确保在php.ini中启用allow_url_fopen
TA贡献1830条经验 获得超9个赞
Komang答案的改进版本(添加引荐来源和用户代理,检查是否可以写入文件),如果可以,则返回true,如果有错误,则返回false:
public function downloadImage($url,$filename){
if(file_exists($filename)){
@unlink($filename);
}
$fp = fopen($filename,'w');
if($fp){
$ch = curl_init ($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$result = parse_url($url);
curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
$raw=curl_exec($ch);
curl_close ($ch);
if($raw){
fwrite($fp, $raw);
}
fclose($fp);
if(!$raw){
@unlink($filename);
return false;
}
return true;
}
return false;
}
- 3 回答
- 0 关注
- 756 浏览
添加回答
举报