解决PHP下载大文件失败,并限制下载速度
标签:comm read ida exists binary arc comment 下载失败 expires
1.问题: PHP在使用readfile函数定义下载文件时候,文件不可以过大,否则会下载失败,文件损坏且不报错;
2.原因: 这个是因为readfile读取文件的时候会把文件放入缓存,导致内存溢出;
3.解决:分段下载,并限制下载速度;
-
-
-
-
-
if (isset($_GET[‘filename‘]) && !empty($_GET[‘filename‘])) {
-
$file_name = $_GET[‘filename‘];
-
$file = __DIR__ . ‘/assets/‘ . $file_name;
-
-
echo ‘what are your searching for?‘;
-
-
-
-
if (file_exists($file) && is_file($file)) {
-
$filesize = filesize($file);
-
header(‘Content-Description: File Transfer‘);
-
header(‘Content-Type: application/octet-stream‘);
-
header(‘Content-Transfer-Encoding: binary‘);
-
header(‘Accept-Ranges: bytes‘);
-
-
header(‘Cache-Control: must-revalidate‘);
-
header(‘Pragma: public‘);
-
header(‘Content-Length: ‘ . $filesize);
-
header(‘Content-Disposition: attachment; filename=‘ . $file_name);
-
-
-
$fp = fopen($file, ‘rb‘);
-
-
-
-
-
-
-
-
$chunk_size = 1024 * 1024 * 2; // 2MB
-
echo fread($fp, $chunk_size);
-
ob_flush(); // 刷新PHP缓冲区到Web服务器
-
flush(); // 刷新Web服务器缓冲区到浏览器
-
-
-
-
-
-
-
echo ‘file not exists or has been removed!‘;
-
-
-
转载于:https://juejin.im/post/5cd445866fb9a031f10ca672
解决PHP下载大文件失败,并限制下载速度
标签:comm read ida exists binary arc comment 下载失败 expires
原文地址:https://www.cnblogs.com/bjzhangshihao/p/13281003.html
评论