php函数file_get_contents超时处理的方法(2013最新整理)

一.增加超时的时间限制
这里需要注意:set_time_limit只是设置你的PHP程序的超时时间,而不是file_get_contents函数读取URL的超时时间。真正的修改 file_get_contents延时可以用resource $context的timeout参数:
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>60,
) );
$context = stream_context_create($opts); $html =file_get_contents('http://www.example.com', false, $context);

二、一次有延时的话那就多试几次
有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;
以上方法对付超时已经OK了。
有人发现了'method'=>”GET”,GET也可以设置成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.jbxue.com', $data);
posted on 2013-06-04 07:04 snowfly123 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/linuxnotes/archive/2013/06/04/3116384.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值