深入php函数file_get_contents超时处理的方法详解

2015-01-24信息快讯网

本篇文章是对php函数file_get_contents超时处理的方法进行了详细的分析介绍,需要的朋友参考下

一.增加超时的时间限制
这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。真正的修改 file_get_contents延时可以用resource $context的timeout参数:
$opts = array(  
    'http'=>array(  
        'method'=>"GET",  
        'timeout'=>60,  
    )  );  
$context = stream_context_create($opts);       $html =file_get_contents('http://www.example.com', false, $context); 

二、一次有延时的话那就多试几次
有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;
以上方法对付超时已经OK了。
有人发现了'method'=>”GET”,GET也可以设置成post,函数如下
   function Post($url, $post = null) 
   { 
       $context = array(); 

      if (is_array($post)) { 
          ksort($post); 

           $context['http'] = array ( 
              'timeout'=>60, 
              'method' => 'POST', 
              'content' => http_build_query($post, '', '&'), 
            ); 
      } 

      return file_get_contents($url, false, stream_context_create($context)); 
   } 

   $data = array ( 
       'name' => 'test', 
       'email' => 'test@gmail.com', 
       'submit' => 'submit', 
   ); 

   echo Post('http://www.example.com', $data); 

PHP CURL获取cookies模拟登录的方法
php Session存储到Redis的方法
单点登录 Ucenter示例分析
教你如何使用php session
php json与xml序列化/反序列化
php加密解密函数authcode的用法详细解析
php session_start()出错原因分析及解决方法
PHP 使用pcntl和libevent 实现Timer功能
php数组转换js数组操作及json_encode的用法详解
PHP中VC6、VC9、TS、NTS版本的区别与用法详解
关于php程序报date()警告的处理(date_default_timezone_set)
PHP file_get_contents设置超时处理方法
php json_encode值中大括号与花括号区别
PHP中time(),date(),mktime()区别介绍
分享下PHP register_globals 值为on与off的理解
php读取本地文件常用函数(fopen与file_get_contents)
解析CI即CodeIgniter框架在Nginx下的重写规则
详解PHP内置访问资源的超时时间 time_out file_get_contents read_file
深入探讨:Nginx 502 Bad Gateway错误的解决方法
基于MySQL到MongoDB简易对照表的详解
作为PHP程序员应该了解MongoDB的五件事
ubuntu10.04配置 nginx+php-fpm模式的详解
spl_autoload_register与autoload的区别详解
深入PHP操作MongoDB的技术总结
解析php中mysql_connect与mysql_pconncet的区别详解
解析php DOMElement 操作xml 文档的实现代码
setcookie中Cannot modify header information-headers already sent by错误的解决方法详解
LotusPhp笔记之:Cookie组件的使用详解
在PHP中设置、使用、删除Cookie的解决方法
基于ubuntu下nginx+php+mysql安装配置的具体操作步骤
基于magic_quotes_gpc与magic_quotes_runtime的区别与使用介绍
关于PHP的相似度计算函数:levenshtein的使用介绍
©2014-2024 dbsqp.com