PHP中file_get_contents高級用法实例

yipeiwu_com6年前PHP代码库

本文实例讲述了PHP中file_get_contents高级用法,分享给大家供大家参考。具体分析如下:

首先解决file_get_contents的超时问题,在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线伺服器而彻底放弃。
这裡就简单介绍两种解决方法:

一、增加超时的时间限制

注意:set_time_limit只是设定你的PHP程式的超时时间,而不是file_get_contents函数读取URL的超时时间。

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

PHP程序代码如下:

$opts = array(
    'http'=>array(
      'method'=>"GET",
      'timeout'=>60,
    )
);

$context = stream_context_create($opts);

$html =file_get_contents('//www.jb51.net', false, $context);
fpassthru($fp);

二、多次尝试

PHP程序代码如下:

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

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

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('//www.jb51.net', $data);

注意文档头的Set_time_out否则整个文档都得超时了。

希望本文所述对大家php程序设计的学习有所帮助。

相关文章

如何获知PHP程序占用多少内存(memory_get_usage)

下面是使用示例: 复制代码 代码如下: <?php echo memory_get_usage(), '<br />'; // 313864 $tmp = str_re...

php实现的日历程序

php实现的日历程序

本文实例讲述了php实现的日历程序。分享给大家供大家参考。具体如下: <?php ////判断$Year和$Month是否为空,如果为空就获取系统当前日期,否则用$_G...

Trying to clone an uncloneable object of class Imagic的解决方法

在windows下安装完后提示:Fatal error: Trying to clone an uncloneable object of class Imagick in C:\www...

解决wincache不支持64位PHP5.5/5.6的问题(提供64位wincache下载) 原创

解决wincache不支持64位PHP5.5/5.6的问题(提供64位wincache下载) 原创

这几天公司有台服务器需要配置,系统是Windows 2008 R2,在IIS上配置环境是64位的PHP5.5,要求支持wincache。原本心想无非就是去wincache的官网下载下来,...

PHP 源代码分析 Zend HashTable详解第1/3页

HashTable在通常的数据结构教材中也称作散列表,哈希表。其基本原理比较简单(如果你对其不熟悉,请查阅随便一本数据结构教材或在网上搜索),但PHP的实现有其独特的地方。理解了Hash...