//$result=httpcopy('http://www.phpernote.com/image/logo.gif');
echo '
';print_r($result);
function httpcopy($url,$file='',$timeout=60){
$file=empty($file)?pathinfo($url,PATHINFO_BASENAME):$file;
$dir=pathinfo($file,PATHINFO_DIRNAME);
!is_dir($dir)&&@mkdir($dir,0755,true);
$url=str_replace(' ',"%20",$url);
$result=array('fileName'=>'','way'=>'','size'=>0,'spendTime'=>0);
$startTime=explode(' ',microtime());
$startTime=(float)$startTime[0]+(float)$startTime[1];
if(function_exists('curl_init')){
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_TIMEOUT,$timeout);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
$temp=curl_exec($ch);
if(@file_put_contents($file,$temp)&&!curl_error($ch)){
$result['fileName']=$file;
$result['way']='curl';
$result['size']=sprintf('%.3f',strlen($temp)/1024);
}
}else{
$opts=array(
'http'=>array(
'method'=>'GET',
'header'=>'',
'timeout'=>$timeout
)
);
$context=stream_context_create($opts);
if(@copy($url,$file,$context)){
$result['fileName']=$file;
$result['way']='copy';
$result['size']=sprintf('%.3f',strlen($context)/1024);
}
}
$endTime=explode(' ',microtime());
$endTime=(float)$endTime[0]+(float)$endTime[1];
$result['spendTime']=round($endTime-$startTime)*1000;//单位:毫秒
return $result;
}
PHP CURL实现远程下载文件到本地,该函数返回结果包括下载耗用的时间,保存的文件名,以及使用的下载方式
str_replace(' ',"%20",$url); 这个是由于如果url有空格,会导致下载文件失败
另一个简单方法:
function upload_get_img($url, $target)
{
$url = str_replace(' ',"%20",$url);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$info = curl_exec($curl);
curl_close($curl);
$newFileName = $target;//保存的本地地址及文件名
$fp2 = @fopen($newFileName, "w");
fwrite($fp2, $info);
fclose($fp2);
return $newFileName;//返回新的文件路径及文件名
}
标签:setopt,CURLOPT,url,result,file,curl,php,下载
来源: https://www.cnblogs.com/init-007/p/13539082.html