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++;

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM