PHP 根据链接下载图片

方法一
$path = '/vagrant/shop/public/images/';
$img = '图片链接';
f(!file_exists($path)) {    // 检查路径是否存在
  if (mkdir($path, 0777, true)) {   // 报错的话,可提出去写加上"@"
     $ch = curl_init();
     $time = time();
     $fp=fopen($path.$time.".jpg", 'w');
     curl_setopt($ch, CURLOPT_URL, $img);
     curl_setopt ($ch, CURLOPT_HEADER, 1);
     curl_setopt($ch, CURLOPT_FAILONERROR, true);
     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 100);
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
     curl_setopt($ch, CURLOPT_FILE, $fp);
     $output = curl_exec($ch);
     $info = curl_getinfo($ch);
     $error = curl_error($ch);
     fclose($fp);
     $size = filesize($path.$time.".jpg");
     curl_close($ch);
     if ($size != $info['size_download']) {
           return "下载失败";
     } else {
           return "下载成功";
     }
   }
}
方法二
$dirs = '图片的url';
$proxy = '获取的代理ip';
// 获取图片
$ch = curl_init();
curl_setopt ($ch, CURLOPT_PROXY, $proxy);  // 可不是用代理
curl_setopt ($ch, CURLOPT_URL, $dirs);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT,10);
$dxycontent = curl_exec($ch);  
   
 // 放入指定文件夹
if ($dxycontent) {
     file_put_contents('路径+自定义图片名称', $dxycontent);   
}

你可能感兴趣的:(PHP 根据链接下载图片)