問(wèn)題描述
關(guān)于如何有效地使用 PHP 下載文件而不是允許直接 HTTP 請(qǐng)求(以確保文件安全、跟蹤下載等),我看到了許多問(wèn)題.
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.).
答案幾乎總是PHP readfile().
- 在 PHP 中可靠地下載大文件
- 如何強(qiáng)制下載大文件又不占用太多內(nèi)存?
- 透明記錄下載的最佳方式?
但是,雖然它在測(cè)試大文件時(shí)效果很好,但當(dāng)它在有數(shù)百個(gè)用戶的實(shí)時(shí)站點(diǎn)上時(shí),下載開(kāi)始掛起并且 PHP 內(nèi)存限制用盡.
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.
那么 readfile()
的工作原理是什么導(dǎo)致內(nèi)存在流量高時(shí)爆炸如此嚴(yán)重?我認(rèn)為它應(yīng)該通過(guò)直接寫(xiě)入輸出緩沖區(qū)來(lái)繞過(guò)大量使用 PHP 內(nèi)存?
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?
(為了澄清,我正在尋找為什么",而不是我能做什么".我認(rèn)為 Apache 的 mod_xsendfile 是最好的規(guī)避方法)
(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 必須讀取文件并將其寫(xiě)入輸出緩沖區(qū).因此,對(duì)于 300Mb 的文件,無(wú)論您編寫(xiě)什么實(shí)現(xiàn)(通過(guò)許多小段或 1 個(gè)大塊),PHP 最終都必須讀取 300Mb 的文件.
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.
如果需要多個(gè)用戶下載文件,就會(huì)出現(xiàn)問(wèn)題.(在一臺(tái)服務(wù)器中,托管服務(wù)提供商會(huì)限制分配給每個(gè)托管用戶的內(nèi)存.由于內(nèi)存如此有限,使用緩沖區(qū)不是一個(gè)好主意.)
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. )
我認(rèn)為使用直接鏈接下載文件對(duì)于大文件來(lái)說(shuō)是一種更好的方法.
I think using the direct link to download a file is a much better approach for big files.
這篇關(guān)于為什么 readfile() 會(huì)耗盡 PHP 內(nèi)存?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!