如何让fopen正确超时?
我有以下 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 stream_context_create() 和 http 上下文选项
超时
。但如果发生超时,fopen()
仍会返回 false,并且stream_get_meta_data()
将不起作用。You can use stream_context_create() and the http context option
timeout
. Butfopen()
will still return false if a timeout occurs, andstream_get_meta_data()
won't work.