/**
* @param $filePath //下载文件的路径
* @param int $readBuffer //分段下载 每次下载的字节数 默认4096bytes
* @param array $allowExt //允许下载的文件类型
* @return void
*/
function downloadFile($filePath, $readBuffer = 4096, $allowExt = ['jpeg', 'jpg', 'peg', 'gif', 'zip', 'rar', 'txt'])
{
//设置文件最长执行时间
set_time_limit(0);
//检测下载文件是否存在 并且可读
if (!is_file($filePath) && !is_readable($filePath)) {
return false;
}
//检测文件类型是否允许下载
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
if (!in_array($ext, $allowExt)) {
return false;
}
if (FALSE!== ($handler = fopen($filePath, 'rb')))
{
//设置指针位置
//fseek($handler, $range);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($filePath));
header('Content-Transfer-Encoding: chunked'); //changed to chunked
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filePath)); //Remove
//Send the content in chunks
while (!feof($handler)) {
//设置文件最长执行时间
echo fread($handler, $readBuffer); //输出文件
flush(); //输出缓冲
ob_flush();
}
fclose($handler);
exit ();
}
return false;
}
本人亲测!!!