Php环境下,超过1GB文件下载解决方案?求大佬给个思路
Php环境下,超过1GB文件下载解决方案?求大佬给个思路https://stackoverflow.com/questions/40419508/how-to-download-big-files-in-php https://zinoui.com/blog/download-large-files-with-php INTRODUCTION
Often a simple task as file downloading may lead to an out of memory. To accomplish successfully file download exists few approaches. Let's see the options:
SEND HEADERS
When starting a file download you need to send the proper headers to the browser.
<?php
function sendHeaders($file, $type, $name=NULL)
{
if (empty($name))
{
$name = basename($file);
}
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Transfer-Encoding: binary');
header('Content-Disposition: attachment; filename="'.$name.'";');
header('Content-Type: ' . $type);
header('Content-Length: ' . filesize($file));
}
?>
SIMPLE DOWNLOAD
Using the file_get_contents() may be it's not the best choise, but should works perfectly for small files. The main disadvantage is that when you store the file contents into a variable, the memory for it is reserved.
<?php
$file = '/path/to/files/photo.jpg';
if (is_file($file))
{
sendHeaders($file, 'image/jpeg', 'My picture.jpg');
$string = @file_get_contents($file);
if ($string !== FALSE) {
echo $string;
}
exit;
}
?>
MORE ADVANCED DOWNLOAD
Using the readfile() will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with ob_get_level().
<?php
$file = '/path/to/files/photo.jpg';
if (is_file($file))
{
sendHeaders($file, 'image/jpeg', 'My picture.jpg');
ob_clean();
flush();
@readfile($file);
exit;
}
?>
CHUNKED DOWNLOAD
This is the old fashioned, but still the most right way to download large files with PHP.
<?php
$file = '/path/to/files/photo.jpg';
if (is_file($file))
{
sendHeaders($file, 'image/jpeg', 'My picture.jpg');
$chunkSize = 1024 * 1024;
$handle = fopen($file, 'rb');
while (!feof($handle))
{
$buffer = fread($handle, $chunkSize);
echo $buffer;
ob_flush();
flush();
}
fclose($handle);
exit;
}
?>
CONCLUSION
Basically all the presented three methods can be used to force downloading a file, but when it comes to large files the chunked download is the most right way. admin 发表于 2019-4-16 11:26 static/image/common/back.gif
INTRODUCTION
Often a simple task as file downloading may lead to an out of memory. To accomplish suc ...
谢谢
页:
[1]