首页 > 解决方案 > 如何强制浏览器下载巨大的 mp4 文件而不是播放它

问题描述

好的,我知道这听起来像是重复的,但事实并非如此。有很多关于下载 mp4 文件而不是通过浏览器播放的问题和答案。

我的问题是我的 mp4 有 1GB 大小,我的服务器有 512 内存和 1 个 CPU,所以这种方法对我不起作用。

这是我当前的代码:

<?php
ini_set('memory_limit', '-1');
$file = $_GET['target'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
readfile($file);
exit;
?>

有没有办法让它发生在一个巨大的文件上?

标签: phpserverdownload

解决方案


您是否尝试过分块下载文件,例如:

$chunk = 256 * 256; // you can play with this - I usually use 1024 * 1024;
$handle = fopen($file, 'rb');
while (!feof($handle))
{
    $data = fread($handle, $chunk);
    echo $data;
    ob_flush();
    flush();
}
fclose($handle);

推荐阅读