php 中file_get_contents超時問題的解決方法


file_get_contents超時我知道最多的原因就是你機器訪問遠程機器過慢,導致php腳本超時了,但也有其它很多原因,下面我來總結file_get_contents超時問題的解決方法總結  全文:http://www.111cn.net/phper/php-cy/49946.htm

 

創建一個可以控制的資源句柄,通過控制資源句柄超時來控制file_get_contents這個方法的超時時間,使用起來很方便,也很簡單。

 代碼如下 復制代碼


$context = stream_context_create(array(
     'http' => array(
      'timeout' => 3000 //超時時間,單位為秒
     ) 
));  
// Fetch the URL's contents 
$contents = file_get_contents('http://www.111cn.net', 0, $context);


一、增加超時的時間限制

這里需要注意:set_time_limit只是設置你的PHP程序的超時時間,而不是file_get_contents函數讀取URL的超時時間。

我一開始以為set_time_limit也能影響到file_get_contents,后來經測試,是無效的。真正的修改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.111cn.net', false, $context);

二、一次有延時的話那就多試幾次

有時候失敗是因為網絡等因素造成,沒有解決辦法,但是可以修改程序,失敗時重試幾次,仍然失敗就放棄,因為file_get_contents()如果失敗將返回 FALSE,所以可以下面這樣編寫代碼:

 

 代碼如下 復制代碼

$cnt=0; 

while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE) $cnt++;


以上方法對付超時已經OK了。那么Post呢?細心點有人發現了'method'=>"GET", 對!是不是能設置成post呢?百度找了下相關資料,還真可以!而且有人寫出了山寨版的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.111cn.net', $data);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM