很多时候我们需要采集其他网站的图片到本地,主要是为了稳定性,以及方便管理。下面提供一段代码。大家参考!
//图片接口地址(这里还是要拿小诗梦开刀)
$url = 'https://******/';
// 图片存放文件夹
$path = 'images/';
$str = file_get_contents($url);
preg_match_all('//',$str,$img);
$imgUrl = 'https://'.$img[2][0];
if(!$imgUrl){
exit(json_encode(array('error'=>'采集失败')));
}
$filename = basename($imgUrl);
$filenames = $path.$filename;
if(file_exists($filenames)){
//文件已经存在
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'202'));
}else{
if(download($imgUrl,$path)){
//采集成功
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'200'));
}else{
//采集失败
echo json_encode(array('url'=>$imgUrl,'filename'=>$filenames,'state'=>'201'));
}
}
function download($url, $path = 'images/')
{
//远程下载保存
if (! file_exists ( $path )) {
mkdir ( "$path", 0777, true );
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$filename = pathinfo($url, PATHINFO_BASENAME);
$resource = fopen($path . $filename, 'a');
fwrite($resource, $file);
fclose($resource);
return true;
}
?>