Home > Backend Development > PHP Tutorial > PHP 下载 file_put_contents vs readfile

PHP 下载 file_put_contents vs readfile

WBOY
Release: 2016-07-28 08:27:51
Original
1481 people have browsed it

set_time_limit(0);
ini_set('memory_limit', '512M');
//获取当前时间
function getTime($convert = true)
{
    return microtime($convert);
}
//获取当前内存
function memory()
{
    return memory_get_usage();
}
$m = memory();
$s = getTime();
$file = file_get_contents("a.zip", true);
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header("Accept-Length: " . filesize('a.zip'));
header('Content-Disposition: attachment; filename="a.zip"');
echo $file;
error_log('file_put_contents:         内存:'.(memory()-$m).',耗时:'.(getTime()-$s).'rn',3,'D:/1.txt');
/* readfile() benchmark */
$m = memory();
$s = getTime();
ob_start();
header('Content-Type: application/octet-stream');
header("Accept-Ranges: bytes");
header("Accept-Length: " . filesize('a.zip'));
header('Content-Disposition: attachment; filename="a.zip"');
header('Content-Transfer-Encoding: binary');
readfile('a.zip');
ob_end_clean();

error_log('readfile:         内存:'.(memory()-$m).',耗时:'.(getTime()-$s).'rn',3,'D:/1.txt');

结果如下:

2k文件
file_put_contents:         内存:2304,耗时:0.00099992752075195
readfile:                  内存:888,耗时: 0.002000093460083
20M文件
file_put_contents:         内存:50126256,耗时:0.21602201461792
readfile:                  内存:896,耗时:0.071007013320923
153M文件
file_put_contents:         内存:321370872,耗时:1.0341031551361
readfile:                  内存:840,耗时:1.9421939849854

结论:相同条件下在下载大文件时使用readfile更省内存,不容易导致php内存溢出问题。

以上就介绍了 PHP 下载 file_put_contents vs readfile,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template