PHP fopen 和file_get_contents 限制了下载速度,为什么?

标签 php fopen file-get-contents bandwidth

我正在尝试使用 PHP 检索远程文件(6MB 文本文件),我注意到使用 fopen 时速度限制为 100KB/s,使用 file_get_contents 时速度限制为 15KB/s。

但是使用来自服务器的 wget 速度超过 5MB/s。

是什么控制了这些速度?

我用 nethogs 检查了实时速度。

最佳答案

wget 本身就非常适合镜像站点,它实际上可以解析页面中的链接并下载文件。

file_get_contents 不发送“连接”HTTP header ,因此远程 Web 服务器默认认为它是一个保持连接并且直到 15 秒才关闭 TCP 流(它可能不是标准值 -取决于服务器 conf)。

如果 HTTP 负载长度达到响应 Content-Length HTTP header 中指定的长度,普通浏览器会认为页面已完全加载。 File_get_contents 不这样做,这很遗憾。

解决方案

所以,如果你想知道解决方案,这里是:

$context = stream_context_create(array('http' => array('header'=>'Connection: close\r\n')));
file_get_contents("http://www.something.com/somepage.html",false,$context);

事情只是告诉远程 Web 服务器在下载完成后关闭连接,因为 file_get_contents 不够智能,无法使用响应 Content-Length HTTP header 自行完成。

关于PHP fopen 和file_get_contents 限制了下载速度,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406749/

相关文章:

php - 无法在 php 的 stdClass 属性中分配闭包

php - 我的网站在整个文件中注入(inject)了 javascript

php - 如何知道客户端在连接到我的服务器时使用的 Internet 协议(protocol) (IP) 版本?

c - 在 malloc 中打开带有路径的文件

php - URL 中带空格的 file_get_contents

php - 从使用 inet_pton() 存储的 MySQL 中获取值

c - 在 C 中拆分 ASCII 文本文件

php - fopen 在公共(public)软件中使用安全吗?

facebook - file_get_contents 不适用于 facebook graph api

php file_put_contents ...我不能在开头追加吗?