【发布时间】:2011-01-04 15:17:11
【问题描述】:
我正在编写一个对外部站点进行 API 调用的 PHP 脚本。但是,如果此站点不可用或请求超时,我希望我的函数返回 false。
我找到了以下内容,但我不确定如何在我的脚本上实现它,因为我使用“file_get_contents”来检索外部文件调用的内容。
Limit execution time of an function or command PHP
$fp = fsockopen("www.example.com", 80);
if (!$fp) {
echo "Unable to open\n";
} else {
fwrite($fp, "GET / HTTP/1.0\r\n\r\n");
stream_set_timeout($fp, 2);
$res = fread($fp, 2000);
$info = stream_get_meta_data($fp);
fclose($fp);
if ($info['timed_out']) {
echo 'Connection timed out!';
} else {
echo $res;
}
}
(来自:http://php.net/manual/en/function.stream-set-timeout.php)
你会如何解决这样的问题?谢谢!
【问题讨论】: