• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

file_get_contents的高級用法分享

php 搞代码 4年前 (2022-01-22) 35次浏览 已收录 0个评论

关于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('http://www.gaodaima.com', false, $context);fpassthru($fp);

二、多

)本文来源gaodai.ma#com搞#代!码网_

搞代gaodaima码次尝试

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' => '[email protected]',    'submit' => 'submit',);echo Post('http://www.gaodaima.com', $data);

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

相关推荐:
php fopen()和file_get_contents()的区别详细讲解

php中比file_get_contents()更优的cURL的实例详解

有关file_get_contents的文章推荐10篇

以上就是file_get_contents的高級用法分享的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:file_get_contents的高級用法分享

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址