飞龙再生

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

如果不动态指定超时时间,file_get_contents 默认超时时间是受 default_socket_timeout 这个 php.ini 属性影响,也就是60秒,所有 php-fpm 就会被堵塞死。

一、增加超时限制

注意: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.example.com', false, $context);
  9. fpassthru($fp); // 不知道是谁哈?

二、多次尝试

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

三、POST请求

以上方法对付超时已经OK了。接下来演示一下用 file_get_contents 实现 Post,如下:

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

四、提交Http头

  1. $context['http'] = array (
  2. 'method' => 'GET',
  3. 'header' => "Accept-language: en\r\n" .
  4. "Cookie: foo=bar\r\n",
  5. );
  6.  
  7. // 注意:Http头每个字段以 \r\n 结尾。
posted on 2015-08-31 12:59  飞龙再生  阅读(836)  评论(0)    收藏  举报