php - 在php中下载大文件的正确方法
问题描述
我正在使用此代码下载大约 5mb 的文件,并且运行良好。
现在当我用它来下载大约10g及以上的文件时。它会冻结浏览器或导致内存问题。我认为最好的方法是以字节为单位读取文件。类似于下面的代码。
$chunk = 1 * 1024 * 1024 // 1m
while (!feof($stream)) {
fwrite(fread($stream, $chunk));
}
我的问题是什么是最好的方法。有人可以帮助我将上面的代码与下面的代码集成。任何可能的解决方案将不胜感激。谢谢
这是小文件下载的工作代码
$output_filename = 'output10g.zip';
$host = "http://localhost/test/10g_file.zip"; //source
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $host);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, false);
echo $result = curl_exec($ch);
curl_close($ch);
$stream = fopen("download/$output_filename", 'wb');
fwrite($stream, $result);
fclose($stream);
解决方案
$download_file = 'movie.mp4';
$chunk = 1024; // 1024 kb/s
if (file_exists($download_file) && is_file($download_file)) {
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($download_file));
header('Content-Disposition: filename=' . $download_file);
$file = fopen($download_file, 'r');
while(!feof($file)) {
print fread($file, round($chunk * 1024));
flush();
}
fclose($file);
}
在 2.5GB 的 MPEG-4 文件上测试。
不要忘记 max_execution_time = 0
在您的 php.ini
文件中设置。
推荐阅读
- python - Discord 机器人未运行和事件循环
- harmonyos - DevEco Studio 中是否有 .xml 的设计选项?
- excel - BI Publisher Excel 模板处理图表中的日期
- node.js - 使用 passport-auth0 进行 MEAN Stack 用户身份验证,在 Anguler 中调用 NodeJs passport-auth0 API
- flutter - Flutter - 在多个提供者之间共享数据
- arrays - 哪种解决方案性能最好,为什么要在复杂列表中查找重复项的数量?
- reactjs - Socket IO 客户端 + React Typescript + Context API 导致 TypeError:无法分配给对象 '# 的只读属性'exports'