php指令碼逾時 結束執行代碼

來源:互聯網
上載者:User

標籤:eth   res   通過   資料流   報錯   logs   str   解決   一個   

函數:stream_context_create ,file_get_content

建立並返回一個文本資料流並應用各種選項,可用於fopen(),file_get_contents()等過程的逾時設定、Proxy 伺服器、請求方式、頭資訊設定的特殊過程。
函數原型: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 && ([email protected]_get_contents(‘http://blog.sina.com/mirze‘))===FALSE) $cnt++;

 

php指令碼逾時 結束執行代碼

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.