zoukankan      html  css  js  c++  java
  • PHP CURL实现远程下载文件到本地

    <?php
    
    //$result=httpcopy('http://www.phpernote.com/image/logo.gif');
    
    echo '<pre>';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实现远程下载文件到本地,该函数返回结果包括下载耗用的时间,保存的文件名,以及使用的下载方式。写的比较粗糙,如果大家有好的建议及改进方案,欢迎留言给我哦!

  • 相关阅读:
    Leetcode 回溯法 典型例题
    LeetCode 回溯法 别人的小结 八皇后 递归
    回溯算法 LEETCODE别人的小结 一八皇后问题
    python学习 面向对象高级编程
    python 学习 面向对象编程
    python 学习 模块
    python 学习 map /reduce
    pyhton 学习 函数式编程
    python学习 函数
    使用dict和set
  • 原文地址:https://www.cnblogs.com/jthb/p/4489297.html
Copyright © 2011-2022 走看看