PHP 下载 file_put_contents vs readfile
程序员文章站
2022-03-26 13:09:57
...
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).'\r\n',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();
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).'\r\n',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).'\r\n',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教程有兴趣的朋友有所帮助。
推荐阅读
-
PHP中创建空文件的代码[file_put_contents vs touch]
-
php运用readfile函数给隐藏下载文件地址增加权限判断
-
php运用readfile函数实现下载文件权限判断
-
php readfile download 下载出现1kb,该如何处理
-
php运用readfile函数实现下载文件权限判断_PHP教程
-
采用header定义为文件然后readfile下载_PHP教程
-
PHP file_put_contents()实现批量下载图片文件和css中图片代码
-
PHP file_put_contents()实现批量下载图片文件和css中图片代码
-
php运用readfile函数实现下载文件权限判断_PHP教程
-
PHP中创建空文件的代码[file_put_contents vs touch]_php技巧