0
点赞
收藏
分享

微信扫一扫

file_get_contents()函数超时处理方法

无聊到学习 2022-04-02 阅读 64


file_get_contents — 将整个文件读入一个字符串

string ​file_get_contents​ ( string ​​$filename​​ [, bool ​​$use_include_path​​ [, resource ​​$context​​ [, int ​​$offset​​ [, int ​​$maxlen​​ ]]]] )

参数

描述

path

必需。规定要读取的文件。

include_path

可选。如果也想在 include_path 中搜寻文件的话,可以将该参数设为 "1"。

context

可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。若使用 null,则忽略。

start

可选。规定在文件中开始读取的位置。该参数是 PHP 5.1 新加的。

max_length

可选。规定读取的字节数。该参数是 PHP 5.1 新加的。


在获取文件的 时候,可能会因为网络等因素,造成获取失败,这里介绍两种方法进行解决

一.增加超时的时间限制 
​这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。真正的修改 file_get_contents延时可以用resource $context的timeout参数: 

<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>60,
) );
$context = stream_context_create($opts);
$html =file_get_contents('http://www.example.com', false, $context);
?>



其中,stream_context_create 作用:创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。 

函数原型:resource stream_context_create ([ array $options [, array $params ]] ) 



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

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



以上方法对付超时已经OK了。

有人发现了'method'=>”GET”,GET也可以设置成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('http://www.example.com', $data);
?>





举报

相关推荐

解决file_get_contents乱码

0 条评论