如何用CURL将文件下载到本地指定文件夹

//获得跳转后的url地址
    function getLocationUrl($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_USERAGENT, "Fiddler");
        curl_setopt($ch, CURLOPT_HEADER, TRUE);
        $response = curl_exec($ch);
        curl_close($ch);
        preg_match_all(‘/^Location:(.*)$/mi‘, $response, $matches);

        return ! empty($matches[1]) ? trim($matches[1][0]) : ‘‘;
    }
function GrabFile($url, $dir, $filename=‘‘){
        if(empty($url)){
            return false;
        }
        $ext = strrchr($url, ‘.‘);
        /*if($ext != ‘.gif‘ && $ext != ".jpg" && $ext != ".bmp"){
            echo "格式不支持!";
            return false;
        }*/

        $dir = realpath($dir);

        /*$start = strrpos($url, "realName=")+9;
        $end = strrpos($url, "&");
        $length = $end-$start;
        $filename = substr($url, $start,$length);*/

        //目录+文件
        $filename = (empty($filename) ? ‘/‘.time().‘‘.$ext : ‘/‘.$filename);
        $filename = $dir . $filename;
        //开始捕捉
        ob_start();
        readfile($url);
        $img = ob_get_contents();
        ob_end_clean();
        $size = strlen($img);
        $fp2 = fopen($filename , "a");
        fwrite($fp2, $img);
        fclose($fp2);
        return $filename;
    }

若下载文件的url有重定向,可先调用第一个方法

$imgpath = "http://www.baidu.com/img/bdlogo.png";

$url = $this->getLocationUrl($imgpath);
$result = $this->GrabFile($url,"E:\Tools\download");//(图片地址,存放目录,存放显示文件名称);
var_dump($result);

文章来自:http://www.cnblogs.com/crystaltu/p/6518391.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3