php脚本超时 结束执行代码

函数:stream_context_create ,file_get_content

创建并返回一个文本数据流并应用各种选项,可用于fopen(),file_get_contents()等过程的超时设置、代理服务器、请求方式、头信息设置的特殊过程。
函数原型:resource stream_context_create ([ array $options [, array $params ]] )

在使用file_get_contents函数的时候,经常会出现超时的情况,在这里要通过查看一下错误提示,看看是哪种错误,比较常见的是读取超时,这种情况大家可以通过一些方法来尽量的避免或者解决。这里就简单介绍两种:

注意: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://blog.sina.com/mirze', false, $context);

如果还有报错可以使用 @ 禁止报错符,如:@file_get_contents

示例:method 可以使用pos和get

function ip_taobao($ip){
    $opt = [
        'http'=>[
            'method'=>'post',
            'timeout'=> 2
        ]
    ];
    $context = stream_context_create($opt);
    $urlTaobao = 'http://ip.taobao.com/service/getIpInfo.php?ip='.$ip;
    $json = @file_get_contents($urlTaobao,false,$context);
    $jsonDecode = json_decode($json);
    if($jsonDecode){
        $data['country'] = $jsonDecode->data->country;
        $data['province'] = $jsonDecode->data->region;
        $data['city'] = $jsonDecode->data->city;
        $data['isp'] = $jsonDecode->data->isp;

    }else{
        $data['country'] = '网络已断开';
    }
    return $data;
}

 

 

二、php代码超时,再次发送请求

有时候失败是因为网络等因素造成,没有解决办法,但是可以修改程序,失败时重试几次,仍然失败就放弃,因为file_get_contents()如果失败将返回 FALSE,所以可以下面这样编写代码:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http://blog.sina.com/mirze'))===FALSE) $cnt++;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值