欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

執(zhí)行、獲取遠(yuǎn)程代碼返回:file_get_contents 超時(shí)處理的問題詳解

 更新時(shí)間:2013年06月25日 16:43:14   作者:  
本篇文章是對(duì)執(zhí)行、獲取遠(yuǎn)程代碼返回:file_get_contents 超時(shí)處理的問題進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
天氣終于晴了,但問題來了。在實(shí)現(xiàn)兩個(gè)站點(diǎn)間用戶數(shù)據(jù)同步,當(dāng)使用php函數(shù) file_get_contents抓取執(zhí)行遠(yuǎn)程頁面時(shí),如果連接超時(shí)將會(huì)輸出一個(gè)Fatal Error或相當(dāng)?shù)穆Y(jié)果導(dǎo)致下面的代碼不能運(yùn)行。先了解一下PHP file_get_contents() 函數(shù)
定義和用法
file_get_contents() 函數(shù)把整個(gè)文件讀入一個(gè)字符串中。
和 file() 一樣,不同的是 file_get_contents() 把文件讀入一個(gè)字符串。
file_get_contents() 函數(shù)是用于將文件的內(nèi)容讀入到一個(gè)字符串中的首選方法。如果操作系統(tǒng)支持,還會(huì)使用內(nèi)存映射技術(shù)來增強(qiáng)性能。
語法
file_get_contents(path,include_path,context,start,max_length)參數(shù) 描述
path 必需。規(guī)定要讀取的文件。
include_path 可選。如果也想在 include_path 中搜尋文件的話,可以將該參數(shù)設(shè)為 "1"。
context 可選。規(guī)定文件句柄的環(huán)境。
context 是一套可以修改流的行為的選項(xiàng)。若使用 null,則忽略。
start 可選。規(guī)定在文件中開始讀取的位置。該參數(shù)是 PHP 5.1 新加的。
max_length 可選。規(guī)定讀取的字節(jié)數(shù)。該參數(shù)是 PHP 5.1 新加的。
說明
對(duì) context 的支持是 PHP 5.0.0 添加的。
針對(duì)超時(shí)或頁面過慢,一般可采取兩個(gè)解決方案:

一. 利用file_get_contents()第三個(gè)參數(shù)
復(fù)制代碼 代碼如下:

$url = "http://zhoz.com/zhoz.php";     
$ctx = stream_context_create(array(     
‘http' => array(‘timeout' => 10)     
    )     
    );     
$result = @file_get_contents($url, 0, $ctx);     
if($result){     
        var_dump($result);     
    }else{     
echo " Buffer is empty";     
    }     
?>  

此方法1,我經(jīng)測(cè)試在本地反映良好,但如果在外網(wǎng)測(cè)試(環(huán)境:中國(guó)→美國(guó)服務(wù)器間)基本都是超時(shí)的情況。
測(cè)試了TimeOut基本沒有用了,建議以下方式

二. 使用curl擴(kuò)展庫(kù)
復(fù)制代碼 代碼如下:

$url = "http://zhoz.com/zhoz.php";     
try {     
echo date(‘Y-m-d h:i:s');     
echo "";     
//$buffer = file_get_contents($url);   
$buffer = zhoz_get_contents($url);     
echo date(‘Y-m-d h:i:s');     
if(emptyempty($buffer)) {     
echo " Buffer is empty";     
        } else {     
echo " Buffer is not empty";     
        }     
    } catch(Exception $e) {     
echo "error ";     
    }     
function zhoz_get_contents($url, $second = 5) {     
$ch = curl_init();     
        curl_setopt($ch,CURLOPT_URL,$url);     
        curl_setopt($ch,CURLOPT_HEADER,0);     
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);     
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);     
$content = curl_exec($ch);     
        curl_close($ch);     
return $content;     
    }     
?>

綜述,根據(jù)系統(tǒng)環(huán)境來選擇到底應(yīng)用哪種方法:
復(fù)制代碼 代碼如下:

function vita_get_url_content($url) {  
if(function_exists(‘file_get_contents')) {  
$file_contents = file_get_contents($url);  
} else {  
$ch = curl_init();  
$timeout = 5;  
curl_setopt ($ch, CURLOPT_URL, $url);  
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);  
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
$file_contents = curl_exec($ch);  
curl_close($ch);  
}  
return $file_contents;  
}  
?> 

相關(guān)文章

最新評(píng)論