php中file_get_contents函数高级用法
发布时间:2022-07-29 11:04:53 所属栏目:PHP教程 来源:互联网
导读:file_get_contents函数我们通常是拿来对文件操作了,下面一起来看看file_get_contents函数的高级使用方法吧. 首先解决file_get_contents的超时问题,在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线伺服器而彻底
file_get_contents函数我们通常是拿来对文件操作了,下面一起来看看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.phpfensi.com', false, $context); fpassthru($fp); 二、多次尝试,PHP程式码: $cnt=0; while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){ $cnt++; } 以上方法对付超时已经OK了,接下来演示一下用file_get_contents实现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.phpfensi.com', $data); 注意档案头的Set_time_out否则整个档案都得超时了 (编辑:甘孜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |