用php下载大文件的正确方法
我用这段代码下载了大约5mb的文件,效果很好 现在我用它来下载10g及以上的文件。它将冻结浏览器或导致内存问题。我认为最好的方法是以字节为单位读取文件。类似下面的代码用php下载大文件的正确方法,php,Php,我用这段代码下载了大约5mb的文件,效果很好 现在我用它来下载10g及以上的文件。它将冻结浏览器或导致内存问题。我认为最好的方法是以字节为单位读取文件。类似下面的代码 $chunk = 1 * 1024 * 1024 // 1m while (!feof($stream)) { fwrite(fread($stream, $chunk)); } 我的问题是,请问最好的方法是什么。有人能帮我把上面的代码和下面的代码集成起来吗。任何可能的解决方案都将不胜感激。谢谢 以下是小文件下载的工作代码 $
$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文件上测试
不要忘记在您的php.ini
文件中设置最大执行时间=0
。我建议使用和处理大型文件
$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文件上测试
不要忘记在您的
php.ini
文件中设置max\u execution\u time=0
。如果您正在下载一个大文件,并且没有将其发送回浏览器,我会在HTTP请求期间进行下载,而是将其作为单独的脚本运行。这样,当下载在后台进行时,HTTP响应可以立即返回。如果您正在下载一个大文件,并且没有将其发送回浏览器,我会在HTTP请求期间进行下载,而是将其作为单独的脚本运行。这样,当下载在后台进行时,HTTP响应可以立即返回。