您的位置:首页 > 其它

stream_set_timeout的使用方法

2011-03-11 00:48 591 查看
PHP函数stream_set_timeout(Stream Functions)作用于读取流时的时间控制。fsockopen函数的timeout只管创建连接时的超时,对于连接后读取流时的超时,则需要用到 stream_set_timeout函数。由于国内的网络环境不是很稳定,尤其是连接国外的时候,不想程序出现Fatal error: Maximum execution time of 30 seconds exceeded in …的错误,该函数尤其有用。stream_set_timeout需配合stream_get_meta_data使用,如果没有timeout, stream_get_meta_data返回数组中time_out为空,反之为1,可根据此判断是否超时。另外由于PHP默认的Maximum execution time为30秒,这是一次执行周期的时间,为了不出现上述的Fatal error,还需要设置一个总的读取流的时间,具体方法参见下面详细代码。

$server="www.yahoo.com";
$port = 80;

$data="GET / HTTP/1.0rn";
$data.="Connection: Closern";
$data.="User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)rnrn";

$start_time = time();
$fp=fsockopen($server, $port, $errno, $errstr, 5);
if (!$fp) {
die("Connect Timeout.n");
} else {
stream_set_blocking($fp, True);
stream_set_timeout($fp, 3);

fputs($fp, "$data");
while (!feof($fp)) {
$text .= fread($fp, 2000);

$diff = time() - $start_time;
if ($diff > 24) {
die("Timeout!n");
}

$status = stream_get_meta_data($fp);
if ($status[’timed_out’]) {
die("Stream Timeout!n");
}
}
}

fclose($fp);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: