[流处理方式访问HTTP]
除了curl,我们还经常自己使用fsockopen、或者是file操作函数来进行HTTP协议的处理,所以,我们对这块的超时处理也是必须的。
一般连接超时可以直接设置,但是流读取超时需要单独处理。
自己写代码处理:
- $tmCurrent = gettimeofday();
- $intUSGone = ($tmCurrent['sec'] - $tmStart['sec']) * 1000000
- + ($tmCurrent['usec'] - $tmStart['usec']);
- if ($intUSGone > $this->_intReadTimeoutUS) {
- return false;
- }
或者使用内置流处理函数 stream_set_timeout() 和 stream_get_meta_data() 处理:
- <?php
- // Timeout in seconds
- $timeout = 5;
- $fp = fsockopen("example.com", 80, $errno, $errstr, $timeout);
- if ($fp) {
- fwrite($fp, "GET / HTTP/1.0\r\n");
- fwrite($fp, "Host: example.com\r\n");
- fwrite($fp, "Connection: Close\r\n\r\n");
- stream_set_blocking($fp, true); //重要,设置为非阻塞模式
- stream_set_timeout($fp,$timeout); //设置超时
- $info = stream_get_meta_data($fp);
- while ((!feof($fp)) && (!$info['timed_out'])) {
- $data .= fgets($fp, 4096);
- $info = stream_get_meta_data($fp);
- ob_flush;
- flush();
- }
- if ($info['timed_out']) {
- echo "Connection Timed Out!";
- } else {
- echo $data;
- }
- }
file_get_contents 超时:
- <?php
- $timeout = array(
- 'http' => array(
- 'timeout' => 5 //设置一个超时时间,单位为秒
- )
- );
- $ctx = stream_context_create($timeout);
- $text = file_get_contents("http://example.com/", 0, $ctx);
- ?>
fopen 超时:
- <?php
- $timeout = array(
- 'http' => array(
- 'timeout' => 5 //设置一个超时时间,单位为秒
- )
- );
- $ctx = stream_context_create($timeout);
- if ($fp = fopen("http://example.com/", "r", false, $ctx)) {
- while( $c = fread($fp, 8192)) {
- echo $c;
- }
- fclose($fp);
- }
- ?>
PHP之友评论