文件下载一直是PHP的痛,传统的做法是 php 读取文件后,通过输出到缓冲区到用户浏览器,这里的弊端显而易见。
首先,PHP-FPM 是堵塞工作的,如果文件比较大,需要耗费一个 PHP 线程处理;
其次,使用 PHP 处理文件下载,非常浪费宝贵的内存空间。
本文就给大家分享一下如何在最短的时间内利用php下载大文件
set_time_limit(0);
ini_set('max_execution_time',0);
//get the http get values and set them as php variables
//download the recordings
if ($_GET['a'] == "download") {
session_cache_limiter('public');
if ($_GET['type'] = "rec") {
$file_path = $_SESSION['switch']['recordings']['dir'].'/'.base64_decode($_GET['filename']);
$filesize = filesize($file_path);
if (file_exists($file_path)) {
// $fd = fopen($file_path, "rb");
if ($_GET['t'] == "bin") {
// header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
// header("Content-Type: application/download");
// header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
}
else {
$file_ext = substr(base64_decode($_GET['filename']), -3);
if ($file_ext == "wav") {
header("Content-Type: audio/x-wav");
}
if ($file_ext == "mp3") {
header("Content-Type: audio/mp3");
}
if ($file_ext == "avi") {
header("Content-Type: video/avi");
}
if ($file_ext == "mp4") {
header("Content-Type: video/mp4");
}
}
// header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
// header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
header("Content-Length: " . $filesize);
ob_clean();
// fpassthru($fd);
//针对大文件,规定每次读取文件的字节数为4096字节,直接输出数据
$read_buffer = 4096;
$handle = fopen($file_path, 'rb');
//总的缓冲的字节数
$sum_buffer = 0;
//只要没到文件尾,就一直读取
while(!feof($handle) && $sum_buffer<$filesize) {
echo fread($handle,$read_buffer);
$sum_buffer += $read_buffer;
}
//关闭句柄
fclose($handle);
}
}
exit;
}
以上就是“php大文件下载方法代码,节省不止一点时间!”的详细内容,想要了解更多php教程欢迎前往编程学习网
扫码二维码 获取免费视频学习资料

- 本文固定链接: http://phpxs.com/post/8499/
- 转载请注明:转载必须在正文中标注并保留原文链接
- 扫码: 扫上方二维码获取免费视频资料
查 看2022高级编程视频教程免费获取