How to get fopen to timeout properly?

佐手、 提交于 2019-12-19 03:20:24

问题


I have the following snippet of php code

if($fp = fopen($url, 'r')) {
    stream_set_timeout($fp, 1); 
    stream_set_blocking($fp, 0);

}
$info = stream_get_meta_data($fp);

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?

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.


回答1:


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);
}


来源:https://stackoverflow.com/questions/2511225/how-to-get-fopen-to-timeout-properly

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!