php 下载文件:
<?php
class WebUtility {
/**
* 下载文件
* @param $file_path string 文件全路径
* @param $file_name string 文件显示名称(带扩展名)
* @param null $file_type 扩展名 zip, jpg, docx
* @return bool
*/
public static function download_file($file_path, $file_name, $file_type = null) {
// test要下载的文件是否存在
if ( !file_exists($file_path) || !is_file($file_path) ) {
echo '您要下载的文件不存在!';
return false;
}
$file_path = trim($file_path);
$file_name = trim($file_name);
if (empty($file_type)) {
$file_type = (function ($file_name) {
$pos = strrpos($file_name, '.');
$ret = substr($file_name, $pos + 1);
return $ret;
})($file_name);
}
switch ($file_type) {
case 'doc':
header("Content-Type: application/msword");
break;
case 'zip':
header("Content-Type: application/x-zip-compressed");
break;
case 'rar':
header("Content-Type: application/x-rar-compressed");
break;
default:
header("Content-Type: application/octet-stream");
break;
}
$file_size = filesize($file_path);
$file_name = urlencode($file_name);
header("Accept-Ranges: bytes");
header("Content-Length: ${file_size}");
header("Content-Disposition:attachment;filename=${file_name}");
header('X-Accel-Redirect: /protected_download' . $file_path);
}
}
function downCurl($url,$filePath)
{
//初始化
$curl = curl_init();
//设置抓取的url
curl_setopt($curl, CURLOPT_URL, $url);
//打开文件描述符
$fp = fopen ($filePath, 'w+');
curl_setopt($curl, CURLOPT_FILE, $fp);
//这个选项是意思是跳转,如果你访问的页面跳转到另一个页面,也会模拟访问。
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl,CURLOPT_TIMEOUT,50);
//执行命令
curl_exec($curl);
//关闭URL请求
curl_close($curl);
//关闭文件描述符
fclose($fp);
}