问题描述
我有以下php代码段
if($fp = fopen($url, 'r')) {
stream_set_timeout($fp, 1);
stream_set_blocking($fp, 0);
}
$info = stream_get_meta_data($fp);
我希望请求在1秒后超时.如果将sleep(20)
放入正在读取的$url
中,它将等待整个20秒,并且永不超时.有没有更好的方法来使用fopen
进行超时?
I'd like the request to timeout after 1 second. If I put a sleep(20)
in my $url
that I'm reading, it just waits the whole 20 seconds and never times out. Is there a better way to do timeouts with fopen
?
如果我在该代码上方使用ini_set('default_socket_timeout',2)
,则它会正确超时,但$info
然后变为null,因此理想情况下,我想使用流函数.
If I use ini_set('default_socket_timeout',2)
above that code it times out properly but $info
then becomes null so ideally I'd like to use the stream functions.
推荐答案
您可以使用 stream_context_create()和 http上下文选项timeout
.但是,如果发生超时,fopen()
仍将返回false,并且stream_get_meta_data()
将不起作用.
You can use stream_context_create() and the http context option timeout
. But fopen()
will still return false if a timeout occurs, and stream_get_meta_data()
won't work.
$url = 'http://...';
$context = stream_context_create( array(
'http'=>array(
'timeout' => 2.0
)
));
$fp = fopen($url, 'r', false, $context);
if ( !$fp ) {
echo '!fopen';
}
else {
$info = stream_get_meta_data($fp);
var_dump($info);
}
这篇关于如何使fopen正确超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!