php用curl实现远程图片下载并保存到本地

实现下载远程图片并把它保存到本地有很多方法,比如file_get_contentscopy方法,如果对方网站设置了防盗链,这些方法就不那么友好了,这里附上使用curl实现下载远程图片并保存到本地的方法。

//方法一
function getImage($url,$save_dir='',$filename='',$type=0){
	if(trim($url)==''){
		return array('file_name'=>'','save_path'=>'','error'=>1);
	}
	if(trim($save_dir)==''){
		$save_dir='./';
	}
	if(trim($filename)==''){//保存文件名
		$ext=strrchr($url,'.');
		if($ext!='.gif'&&$ext!='.jpg'){
			return array('file_name'=>'','save_path'=>'','error'=>3);
		}
		$filename=time().$ext;
	}
	if(0!==strrpos($save_dir,'/')){
		$save_dir.='/';
	}
	//创建保存目录
	if(!file_exists($save_dir)&&!mkdir($save_dir,0777,true)){
		return array('file_name'=>'','save_path'=>'','error'=>5);
	}
	//获取远程文件所采用的方法 
	if($type){
		$ch=curl_init();
		$timeout=5;
		curl_setopt($ch,CURLOPT_URL,$url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
		$img=curl_exec($ch);
		curl_close($ch);
	}else{
		ob_start(); 
		readfile($url);
		$img=ob_get_contents(); 
		ob_end_clean(); 
	}
	//$size=strlen($img);
	//文件大小 
	$fp2=@fopen($save_dir.$filename,'a');
	fwrite($fp2,$img);
	fclose($fp2);
	unset($img,$url);
	return array('file_name'=>$filename,'save_path'=>$save_dir.$filename,'error'=>0);
}


//方法二
function api_image($page,$n){
        $url = "http://api.avatardata.cn/Joke/QueryImgByTime";
        $params = "key=d1091150c206481c83e30ecd52078d02&page=".$page."&rows=50&sort=desc&time=1496656686";
    $ch = curl_init();

    curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 60 );
    curl_setopt( $ch, CURLOPT_USERAGENT , '' );
    curl_setopt( $ch, CURLOPT_TIMEOUT , 60);
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );

    $response = curl_exec( $ch );
    $response = json_decode($response);
    curl_close( $ch );
    if($data = $response->result){
        return $data;
    }else{
        echo "\n";var_dump('end by:'.$page.'image_id:'.$n);exit;
    }
}

$b = 6949;
for ($i=19; $i >0 ; $i--) {
    echo 'page='.$i.'--image_id='.$b."\n";
    $data = api_image($i,$b);
foreach ($data as $value) {
    $uri = basename($value->url);
    $file_name = substr($uri,strpos($uri,'=')+1);
    $ext = pathinfo($file_name,PATHINFO_EXTENSION);
    // copy(htmlspecialchars_decode($value->url),$_SERVER['DOCUMENT_ROOT'].'joke_image/'.md5($b).$ext);
    if($ext == 'gif'){
    copy(htmlspecialchars_decode($value->url),'/data/httpd/www/Suvan/suixingbiji/joke_image/'.$b++.'.'.$ext);
    }else{
    continue;
    }
    }
}

评论

评论正在提交中...请稍后
评论提交成功...