【发布时间】:2011-04-11 00:03:20
【问题描述】:
$url = 'http://a.url/i-know-is-down';
//ini_set('default_socket_timeout', 5);
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 5,
'ignore_errors' => true
)
)
);
$start = microtime(true);
$content = @file_get_contents($url, false, $ctx);
$end = microtime(true);
echo $end - $start, "\n";
我得到的响应一般是 21.232 segs,不应该是五秒左右???
取消注释 ini_set 行根本没有帮助。
【问题讨论】:
-
您能否尝试关闭“ignore_errors”标志以及静默@file_get_contents() 调用,看看是否有任何明显的错误弹出?
-
@Mahdi.M:我无法关闭
ingnore_errors,因为我需要区分 404 错误和连接问题产生的错误。让我重新表述一下。如果 ingnore_errors 关闭并且服务器返回 404 $content 将是错误的,我需要知道 $content 是否为 false 因为 404 错误或连接错误。当我抑制 @ 运算符时显示的错误是一个通用的,例如file_get_contents(filename): failed to open stream -
根据经验,您永远不需要使用@。如果它对您的应用程序至关重要,那么您可能以错误的方式编写它。不总是,但该死的经常!
-
@Cesar:如果需要区分HTTP错误码,请在调用
file_get_contents()后阅读$http_response_header。它被填充为服务器返回的 HTTP 标头数组。除了服务器连接问题(服务器未找到、超时、连接被拒绝等)之外,您可以获得所有错误
标签: php file-get-contents connection-timeout