How to force browser to download HUGE mp4 file instead of playing it

风流意气都作罢 提交于 2019-12-08 13:51:00

问题


Okay , I know it sounds like duplicate but it's not. there's a lot of questions and answers about downloading a mp4 file instead of playing it by browser.

my issue is my mp4 has 1GB size and my server has 512 ram and 1 CPU so , this methods are not working for me.

Here's my current code :

<?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;
?>

Is there any way to make it happen on a huge file ?


回答1:


Have you tried downloading the file in chunks, e.g.:

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



回答2:


Thanks to jibsteroos final working code is :

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

?>

Usage Example :

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



来源:https://stackoverflow.com/questions/58070029/how-to-force-browser-to-download-huge-mp4-file-instead-of-playing-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!