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