stream_get_contents卡在持久(KeepAlive)连接上

时间:2012-06-22 20:42:40

标签: php

stream_get_contents似乎没有正确处理持久性(KeepAlive)连接。它在返回之前等待连接超时。默认情况下,Apache 2.2的KeepAliveTimeout为5秒。我能做些什么吗? (除了在服务器上禁用KeepAlive,或使用protocol_version 1.0)

$opts = array('http' =>
    array(
        'method' => 'GET',
        'protocol_version' => 1.1,
    )
);
$context = stream_context_create($opts);
$stream = fopen('http://google.com', 'r', false, $context);
$metadata = stream_get_meta_data($stream);
$data = stream_get_contents($stream);
fclose($stream);

感谢。

1 个答案:

答案 0 :(得分:2)

$opts = array('http' =>
    array(
        'method' => 'GET',
        'protocol_version' => 1.1,
        'header' => 'Connection: close'
    )
);

Connection: close告诉服务器不要使用持久连接,并在发送响应后删除TCP连接。

这是part of the HTTP/1.1 standard,正如PHP manual所说:

  

如果[protocol_version]设置为1.1,则您有责任遵守1.1。