首页 新闻 会员 周边

php stream_context_create 函数设置超时问题

0
悬赏园豆:20 [已解决问题] 解决于 2012-04-19 14:32

请问:

    1、 如何设置 file_get_contents() 函数的超时时间?

    2、能否设置 file_get_contents() 函数的毫秒级超时,如果能,如何实现?

    3、以下描述的问题是什么情况?

   

使用 stream_context_create 方法设置 file_get_contents 函数超时的时候:

<?php
$ctx = stream_context_create(array(
    'http' => array(
        'timeout' => 1  // 超时
        )
    )
);

$i = microTime();
$size = file_get_contents("http://****{图*片*地*址}******.jpg",0,$ctx);
$e = microTime() - $i;
echo $e;

// 获得微秒时间戳
function microTime()
{
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
}

?>

    发现 当 timeout 设置为 1 时,只有当访问时长 $e 超过2s时才会报错:

Warning: file_get_contents(********): failed to open stream: HTTP request failed!  in /usr/home/*******/test.php

    同理 当 timeout 设置为 2 时,访问时长 $e 的值可能为 2.4s、2.6s等(小于3s,超过3s时报错)。

 

魇靥的主页 魇靥 | 初学一级 | 园豆:195
提问于:2012-04-17 18:19
< >
分享
最佳答案
0

可以使用stream_set_timeout

bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )
收获园豆:20
dudu | 高人七级 |园豆:30994 | 2012-04-18 10:30

stream_set_timeout有办法和file_get_contents函数结合使用吗? 还是一定要针对一个stream类的对象使用?

魇靥 | 园豆:195 (初学一级) | 2012-04-18 11:26

@魇靥: 在 file_get_contents 之前 stream_set_timeout

dudu | 园豆:30994 (高人七级) | 2012-04-18 11:28

@dudu: 还有一点疑问:
bool stream_set_timeout ( resource $stream , int $seconds [, int $microseconds = 0 ] )
第一个参数是 resource $stream,对于file_get_contents函数来说,要怎么传这个参数,能够给一个简单的例子说明一下?多谢~

魇靥 | 园豆:195 (初学一级) | 2012-04-18 13:30

@魇靥: 

参考这篇文章(Set time out while downloading files in PHP)吧,几种实现方式都有示例代码。

dudu | 园豆:30994 (高人七级) | 2012-04-18 13:40

@dudu: 嗯,多谢,看起来file_get_contents 和 stream_set_timeout是不能搭配使用的,而且很可能file_get_contents函数并不能实现毫秒超时的设置。还是curl好用。

魇靥 | 园豆:195 (初学一级) | 2012-04-18 14:00
其他回答(1)
0

看来该问题无法按照期望解决了

魇靥 | 园豆:195 (初学一级) | 2012-04-19 14:31
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册