php脚本超时 结束执行代码
函數(shù):stream_context_create ,file_get_content
創(chuàng)建并返回一個(gè)文本數(shù)據(jù)流并應(yīng)用各種選項(xiàng),可用于fopen(),file_get_contents()等過程的超時(shí)設(shè)置、代理服務(wù)器、請求方式、頭信息設(shè)置的特殊過程。
函數(shù)原型:resource?stream_context_create?([?array?$options?[,?array?$params?]]?)
在使用file_get_contents函數(shù)的時(shí)候,經(jīng)常會(huì)出現(xiàn)超時(shí)的情況,在這里要通過查看一下錯(cuò)誤提示,看看是哪種錯(cuò)誤,比較常見的是讀取超時(shí),這種情況大家可以通過一些方法來盡量的避免或者解決。這里就簡單介紹兩種:
注意:set_time_limit只是設(shè)置你的PHP程序的超時(shí)時(shí)間,而不是file_get_contents函數(shù)讀取URL的超時(shí)時(shí)間。一開始以為set_time_limit也能影響到file_get_contents,后來經(jīng)測試,是無效的。真正的修改?file_get_contents延時(shí)可以用resource?$context的timeout參數(shù):
?
一、php代碼超時(shí)結(jié)束執(zhí)行
常規(guī)代碼:
$opts = array('http'=>array('method'=>"GET",'timeout'=>60,) ); //創(chuàng)建數(shù)據(jù)流上下文 $context = stream_context_create($opts);$html =file_get_contents('http://blog.sina.com/mirze', false, $context);如果還有報(bào)錯(cuò)可以使用 @ 禁止報(bào)錯(cuò)符,如:@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'] = '網(wǎng)絡(luò)已斷開';}return $data; }?
?
二、php代碼超時(shí),再次發(fā)送請求
有時(shí)候失敗是因?yàn)榫W(wǎng)絡(luò)等因素造成,沒有解決辦法,但是可以修改程序,失敗時(shí)重試幾次,仍然失敗就放棄,因?yàn)閒ile_get_contents()如果失敗將返回?FALSE,所以可以下面這樣編寫代碼:
$cnt=0;
while($cnt?<?3?&&?($str=@file_get_contents('http://blog.sina.com/mirze'))===FALSE)?$cnt++;
?
總結(jié)
以上是生活随笔為你收集整理的php脚本超时 结束执行代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zabbix增加手机端4个url地址的返
- 下一篇: CentOS7入门_安装并配置mysql