若直接調用下載文件的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; }