如何强制浏览器下载巨大的mp4文件而不是播放它

时间:2019-09-23 20:51:23

标签: php server download

好的,我知道这听起来像是重复的,但事实并非如此。 关于下载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;
?>

有什么办法可以使它在巨大的文件上发生?

2 个答案:

答案 0 :(得分:1)

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

$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);

答案 1 :(得分:0)

感谢 jibsteroos 的最终工作代码是:

download.php:

<?php
$file = "videos\\" . $_GET['target'];
header ("Content-type: octet/stream");
header ("Content-disposition: attachment; filename=".$file.";");
header("Content-Length: ".filesize($file));
$chunk = 512* 512; 
$handle = fopen($file, 'rb');
while (!feof($handle))
{
    $data = fread($handle, $chunk);
    echo $data;
    ob_flush();
    flush();
}
fclose($handle);

?>

用法示例:

  

www.example.com/download.php?target=huge_video.mp4

相关问题