作为程序员一定要保持良好的睡眠,才能好编程

处理远程图片下载

发布时间:2017-09-11






//处理远程图片下载
//$url格式为   $url = 'https://img.weixiaoqu.com/images/uploads/201708/7db23487c0c16bbb642afe9a6e2ab061.jpg';

function download_img($url)
{
    $file_path =dirname($_SERVER['SCRIPT_FILENAME'])."/upload/sq/".basename($url);
    if(!file_exists($file_path)){
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        ob_start ();
        curl_exec ( $ch );
        $return_content = ob_get_contents ();
        ob_end_clean ();
        $return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
        $fp= @fopen($file_path,"a"); //将文件绑定到流
        fwrite($fp,$return_content); //写入文件
        fclose($fp);
        return $file_path;
    }else{
        return $file_path;
    }
}
function download_img($url, $filename) {
  $file_path = dirname(__DIR__) . DIRECTORY_SEPARATOR . 'biaoqing' . DIRECTORY_SEPARATOR . $filename;
  $rh = fopen($url, 'rb');
  $wh = fopen($file_path, 'wb');
  if ($rh===false || $wh===false) {
    return false;
  }

  while (!feof($rh)) {
    if (fwrite($wh, fread($rh, 1024)) === FALSE) {
      // 'Download error: Cannot write to file ('.$file_target.')';
      return true;
    }
  }
  fclose($rh);
  fclose($wh);
  return $file_path;
}