如何使fopen正确超时? [英] How to get fopen to timeout properly?

查看:242
本文介绍了如何使fopen正确超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下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正确超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆