php 更快的 fopen 或 file_get_contents?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7806561/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
faster fopen or file_get_contents?
提问by Rami Dabain
i am running multiple websites with high traffic , as a requirement , all images are downloaded via image.php?id=IMAGE_ID_HERE
.
If you ever done that before , you know that that file will be reading the file image and echoing it to the browser with special headers .
我正在运行多个高流量网站,根据要求,所有图像都通过image.php?id=IMAGE_ID_HERE
. 如果您以前这样做过,您就会知道该文件将读取文件图像并使用特殊标题将其回显到浏览器。
My problem is , the load on the server is very high (150-200) and TOP command shows multiple instances of image.php , so image.php is running slow !
我的问题是,服务器上的负载非常高(150-200)并且 TOP 命令显示 image.php 的多个实例,因此 image.php 运行缓慢!
the problem probably is fopen
loading the image to the memory before sending it to the client. How to read a file and pass it through directly?
问题可能是fopen
在将图像发送到客户端之前将图像加载到内存中。如何读取文件并直接传递它?
Thank you guys
谢谢你们
UPDATE
更新
After you optimized the code, used caching wherever possible, do create a CDN . couple of servers, sync methods, load balancers and no need to worry about requests anymore :)
优化代码后,尽可能使用缓存,创建一个 CDN 。几个服务器、同步方法、负载平衡器,无需再担心请求:)
回答by
fopen and file_get_contents are nearly equivalent
fopen 和 file_get_contents 几乎等价
to speed up with consistence the page load you can use
为了加快一致性,您可以使用页面加载
or, even better
或者,甚至更好
with those functions, content of file is printed directly, byte per byte
使用这些函数,文件的内容被直接打印,每字节一个字节
as opposed to file_get_contents, for example, where you store the whole data inside a variable
与 file_get_contents 相反,例如,您将整个数据存储在一个变量中
$var = file_get_contents();
so, to make these work correctly you will need to disable output buffering (otherwise it would make readfile() pointless) in the page that serves the images
因此,为了使这些正常工作,您需要在提供图像的页面中禁用输出缓冲(否则会使 readfile() 变得毫无意义)
hope this helps!
希望这可以帮助!
回答by Paté
Why dont you cache the image content with apc ?
为什么不使用 apc 缓存图像内容?
if(!apc_exists('img_'.$id)){
apc_store('img_'.$id,file_get_content(...));
}
echo apc_fetch('img_'.$id);
this way image content will not be read from your disk more than once.
这样图像内容将不会从您的磁盘中读取多次。