PHP头条
热点:

[流处理方式访问HTTP] 

除了curl,我们还经常自己使用fsockopen、或者是file操作函数来进行HTTP协议的处理,所以,我们对这块的超时处理也是必须的。

一般连接超时可以直接设置,但是流读取超时需要单独处理。

自己写代码处理:

  1. $tmCurrent = gettimeofday();  
  2.  
  3.             $intUSGone = ($tmCurrent['sec'] - $tmStart['sec']) * 1000000  
  4.  
  5.                     + ($tmCurrent['usec'] - $tmStart['usec']);  
  6.  
  7.             if ($intUSGone > $this->_intReadTimeoutUS) {  
  8.  
  9.                 return false;  
  10.  
  11.             } 

或者使用内置流处理函数 stream_set_timeout() 和 stream_get_meta_data() 处理:

  1. <?php    
  2. // Timeout in seconds   
  3.  
  4. $timeout = 5;   
  5.  
  6. $fp = fsockopen("example.com", 80, $errno$errstr$timeout);   
  7.  
  8. if ($fp) {   
  9.  
  10.         fwrite($fp"GET / HTTP/1.0\r\n");   
  11.  
  12.         fwrite($fp"Host: example.com\r\n");   
  13.  
  14.         fwrite($fp"Connection: Close\r\n\r\n");   
  15.  
  16.         stream_set_blocking($fp, true);   //重要,设置为非阻塞模式  
  17.  
  18.         stream_set_timeout($fp,$timeout);   //设置超时  
  19.  
  20.         $info = stream_get_meta_data($fp);   
  21.  
  22.         while ((!feof($fp)) && (!$info['timed_out'])) {   
  23.  
  24.                 $data .= fgets($fp, 4096);   
  25.  
  26.                 $info = stream_get_meta_data($fp);   
  27.  
  28.                 ob_flush;   
  29.  
  30.                 flush();   
  31.  
  32.         }   
  33.  
  34.         if ($info['timed_out']) {   
  35.  
  36.                 echo "Connection Timed Out!";   
  37.  
  38.         } else {   
  39.  
  40.                 echo $data;   
  41.  
  42.         }   
  43.  
  44. }  

file_get_contents 超时:

  1. <?php   
  2. $timeout = array(  
  3.  
  4.     'http' => array(  
  5.  
  6.         'timeout' => 5 //设置一个超时时间,单位为秒  
  7.  
  8.     )  
  9.  
  10. );  
  11.  
  12. $ctx = stream_context_create($timeout);  
  13.  
  14. $text = file_get_contents("http://example.com/", 0, $ctx);  
  15.  
  16. ?>  

fopen 超时:

  1. <?php   
  2. $timeout = array(  
  3.  
  4.     'http' => array(  
  5.  
  6.         'timeout' => 5 //设置一个超时时间,单位为秒  
  7.  
  8.     )  
  9.  
  10. );  
  11.  
  12. $ctx = stream_context_create($timeout);  
  13.  
  14. if ($fp = fopen("http://example.com/""r", false, $ctx)) {  
  15.  
  16.   while$c = fread($fp, 8192)) {  
  17.  
  18.     echo $c;  
  19.  
  20.   }  
  21.  
  22.   fclose($fp);  
  23.  
  24. }  
  25.  
  26. ?> 


www.phpzy.comtrue/php/2425.htmlTechArticle[流处理方式访问HTTP] 除了curl,我们还经常自己使用fsockopen、或者是file操作函数来进行HTTP协议的处理,所以,我们对这块的超时处理也是必须的。 一般连...

相关文章

相关频道:

PHP之友评论

今天推荐