当前位置:首页 > PHP教程 > php应用 > 列表

php 中file_get_contents超时问题的解决方法

发布:smiling 来源: PHP粉丝网  添加日期:2014-07-18 11:16:16 浏览: 评论:0 

file_get_contents超时我知道最多的原因就是你机器访问远程机器过慢,导致php脚本超时了,但也有其它很多原因,下面我来总结file_get_contents超时问题的解决方法总结.

创建一个可以控制的资源句柄,通过控制资源句柄超时来控制file_get_contents这个方法的超时时间,使用起来很方便,也很简单,代码如下:

  1. $context = stream_context_create(array( 
  2.      'http' => array( 
  3.       'timeout' => 3000 //超时时间,单位为秒 
  4.      )  
  5. ));   
  6. // Fetch the URL's contents  
  7. $contents = file_get_contents('http://www.phpfensi.com', 0, $context); 

一、增加超时的时间限制

这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间.

我一开始以为set_time_limit也能影响到file_get_contents,后来经测试,是无效的,真正的修改file_get_contents延时可以用resource $context的timeout参数,代码如下 :

  1. $opts = array( 
  2. 'http'=>array( 
  3. 'method'=>"GET", 
  4. 'timeout'=>60, 
  5. ) 
  6. ); 
  7. $context = stream_context_create($opts); 
  8. $html =file_get_contents('http://www.phpfensi.com', false, $context); 

二、一次有延时的话那就多试几次

有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:

  1. $cnt=0;  
  2. while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++; 

以上方法对付超时已经OK了,那么Post呢?细心点有人发现了'method'=>"GET",对!是不是能设置成post呢?百度找了下相关资料,还真可以!而且有人写出了山寨版的post传值函数,如下:

  1. function Post($url, $post = null) 
  2. { 
  3. $context = array(); 
  4.  
  5. if (is_array($post)) 
  6. { 
  7. ksort($post); 
  8.  
  9. $context['http'] = array 
  10. ( 
  11.  
  12. 'timeout'=>60, 
  13. 'method' => 'POST', 
  14. 'content' => http_build_query($post, '', '&'), 
  15. ); 
  16. } 
  17.  
  18. return file_get_contents($url, false, stream_context_create($context)); 
  19. } 
  20.  
  21. $data = array 
  22. ( 
  23. 'name' => 'test', 
  24. 'email' => 'test@gmail.com', 
  25. 'submit' => 'submit', 
  26. ); 
  27.  
  28. echo Post('http://www.phpfensi.com', $data); 

Tags: file_get_contents超时

分享到: