3 回答

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超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貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個贊
Komang答案的改進(jìn)版本(添加引薦來源和用戶代理,檢查是否可以寫入文件),如果可以,則返回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 關(guān)注
- 780 瀏覽
添加回答
舉報(bào)