欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP中file_get_contents高級用法实例

程序员文章站 2023-02-08 09:54:53
本文实例讲述了php中file_get_contents高级用法,分享给大家供大家参考。具体分析如下: 首先解决file_get_contents的超时问题,在超时返回错...

本文实例讲述了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程序设计的学习有所帮助。