如何让fopen正确超时?

发布于 2024-08-26 14:46:09 字数 441 浏览 5 评论 0原文

我有以下 php 代码片段,

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

}
$info = stream_get_meta_data($fp);

我希望请求在 1 秒后超时。如果我在正在阅读的 $url 中放入 sleep(20) ,它只会等待整整 20 秒,并且永远不会超时。有没有更好的方法来使用 fopen 进行超时?

如果我在该代码上方使用 ini_set('default_socket_timeout',2) ,它会正确超时,但 $info 然后变为 null,所以理想情况下我想使用流函数。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你不是我要的菜∠ 2024-09-02 14:46:09

您可以使用 stream_context_create()http 上下文选项超时。但如果发生超时,fopen() 仍会返回 false,并且 stream_get_meta_data() 将不起作用。

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文