如何用CURL將文件下載到本地指定文件夾



若直接調用下載文件的url有重定向,則需先調用第一個方法,獲取到跳轉后的url,才可直接下載。否則需要手動點擊瀏覽器的下載確定按鈕。

調用示例:

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

$url = $this->getLocationUrl($imgpath); //獲取跳轉后的url地址,若url地址無后續跳轉,可忽略此步

$result = $this->GrabFile($url,"E:\Tools\download");//(圖片地址,存放目錄,存放顯示文件名稱);

var_dump($result);

 

  //獲得跳轉后的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, '.'); $dir = realpath($dir); //目錄+文件 $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; }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM