PHP file_get_contents忽略超时? [英] PHP file_get_contents ignoring timeout?
问题描述
$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段,应该不超过5秒钟?
the response I get is generally 21.232 segs, shouldn't be about five seconds???
取消注释ini_set行根本没有帮助.
Uncommenting the ini_set line don't help at all.
推荐答案
您正在使用socket_create_context
设置 read 超时.如果您尝试访问的 page 不存在,则服务器将允许您连接并给您404.但是,如果 site 不存在(赢得't解析或在其后面没有Web服务器),则file_get_contents()
将忽略读取超时,因为它甚至还没有超时连接到它.
You are setting the read timeout with socket_create_context
. If the page you are trying to access doesn't exist then the server will let you connect and give you a 404. However, if the site doesn't exist (won't resolve or no web server behind it), then file_get_contents()
will ignore read timeout because it hasn't even timed out connecting to it yet.
我认为您不能在file_get_contents
中设置连接超时.我最近重写了一些使用fsockopen()
的代码,正是因为它允许您指定连接超时
I don't think you can set the connection timeout in file_get_contents
. I recently rewrote some code to use fsockopen()
exactly because it lets you specify connect timeout
$connTimeout = 30 ;
$fp = fsockopen($hostname, $port, $errno, $errstr, $connTimeout);
当然,要转到fsockopen,将需要您从一个循环中依次退出fread()
,从而使您的代码稍微复杂些.但是,在使用stream_get_meta_data()
Ofcourse going to fsockopen will require you to then fread()
from it in a loop, compicating your code slightly. It does give you more control, however, on detecting read timeouts while reading from it using stream_get_meta_data()
http://php.net/stream_get_meta_data
这篇关于PHP file_get_contents忽略超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!