为什么readfile()耗尽了PHP内存? [英] Why does readfile() exhaust PHP memory?

查看:266
本文介绍了为什么readfile()耗尽了PHP内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到许多有关如何有效使用PHP下载文件而不是允许直接HTTP请求(保持文件安全,跟踪下载等)的问题.

答案几乎总是 PHP readfile().

但是,尽管它在测试大型文件时效果很好,但是当它在具有数百个用户的实时站点上时,下载开始挂起,并且PHP内存限制已用尽.

那么readfile()的工作原理是什么呢?当流量很高时,导致内存崩溃的情况非常严重?我以为应该通过直接写入输出缓冲区来绕过大量使用PHP内存?

(为澄清起见,我正在寻找为什么",而不是我该怎么办".我认为Apache的解决方案

Description
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
Reads a file and writes it to the output buffer*.

PHP必须读取文件并将其写入输出缓冲区. 因此,对于300Mb的文件,无论您编写了什么实现(按许多小段或按一个大块),PHP最终都必须读取300Mb的文件.

如果多个用户必须下载文件,则将出现问题. (在一台服务器中,托管服务提供商将限制分配给每个托管用户的内存.由于内存有限,使用缓冲区并不是一个好主意.)

我认为使用直接链接下载文件对于大文件来说是一种更好的方法.

I've seen many questions about how to efficiently use PHP to download files rather than allowing direct HTTP requests (to keep files secure, to track downloads, etc.).

The answer is almost always PHP readfile().

BUT, although it works great during testing with huge files, when it's on a live site with hundreds of users, downloads start to hang and PHP memory limits are exhausted.

So what is it about how readfile() works that causes memory to blow up so bad when traffic is high? I thought it's supposed to bypass heavy use of PHP memory by writing directly to the output buffer?

EDIT: (To clarify, I'm looking for a "why", not "what can I do". I think that Apache's mod_xsendfile is the best way to circumvent)

解决方案

Description
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
Reads a file and writes it to the output buffer*.

PHP has to read the file and it writes to the output buffer. So, for 300Mb file, no matter what the implementation you wrote (by many small segments, or by 1 big chunk) PHP has to read through 300Mb of file eventually.

If multiple user has to download the file, there will be a problem. (In one server, hosting providers will limit memory given to each hosting user. With such limited memory, using buffer is not going to be a good idea. )

I think using the direct link to download a file is a much better approach for big files.

这篇关于为什么readfile()耗尽了PHP内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆