Maison  >  Article  >  développement back-end  >  PHP函数file_get_contents高級用法

PHP函数file_get_contents高級用法

WBOY
WBOYoriginal
2016-06-20 13:01:36840parcourir

本文实例讲述了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程序代码如下:

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

二、多次尝试

PHP程序代码如下:

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

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

三、用file_get_contents实现Post

如下:PHP程序代码

<p><?php</p><p>function Post($url, $post = null){ </p><p>$context = array(); </p><p>if (is_array($post)) { </p><p>ksort($post); </p><p>$context['http'] = array ( 'timeout'=>60, 'method' => 'POST', 'content' => http_build_query($post, '', '&'), ); </p><p>} </p><p>return file_get_contents($url, false, stream_context_create($context)); } </p><p>$data = array ( 'name' => 'test', 'email' => , 'submit' => 'submit', ); </p><p>echo Post('http://www.scutephp.com', $data);</p>

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


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn