首页 > 解决方案 > 在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);

标签: php

解决方案


我推荐使用fopen()fread()来处理大文件。

$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 文件中设置。


推荐阅读