curl_setopt($ch,CURLOPT_TIMEOUT,60);//只需要設置一個秒的數量就可以
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
curl_setopt($ch,CURLOPT_USERAGENT,$defined_vars['HTTP_USER_AGENT']);
curl普通秒級超時使用:
curl_setopt($ch,CURLOPT_TIMEOUT,60);
curl如果需要進行毫秒超時,需要增加:
curl_easy_setopt(curl,CURLOPT_NOSIGNAL,1L);
或者是:
curl_setopt($ch,CURLOPT_NOSIGNAL,true);是可以支持毫秒級別超時設置的
curl一個毫秒級超時的例子:
<?php if(!isset($_GET['foo'])){ //Client $ch=curl_init('http://example.com/'); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_NOSIGNAL,1);//注意,毫秒超時一定要設置這個 curl_setopt($ch,CURLOPT_TIMEOUT_MS,200);//超時毫秒,cURL7.16.2中被加入。從PHP5.2.3起可使用 $data=curl_exec($ch); $curl_errno=curl_errno($ch); $curl_error=curl_error($ch); curl_close($ch); if($curl_errno>0){ echo"cURLError($curl_errno):$curl_errorn"; }else{ echo"Datareceived:$datan"; } }else{ //Server sleep(10); echo"Done."; } ?> |
其他一些技巧:
1. 按照經驗總結是:cURL版本>=libcurl/7.21.0版本,毫秒級超時是一定生效的,切記。
2. curl_multi的毫秒級超時也有問題。。單次訪問是支持ms級超時的,curl_multi并行調多個會不準
[流處理方式訪問HTTP]
除了curl,我們還經常自己使用fsockopen、或者是file操作函數來進行HTTP協議的處理,所以,我們對這塊的超時處理也是必須的。
一般連接超時可以直接設置,但是流讀取超時需要單獨處理。
自己寫代碼處理:
$tmCurrent=gettimeofday();
$intUSGone=($tmCurrent['sec']-$tmStart['sec'])*1000000
+($tmCurrent['usec']-$tmStart['usec']);
if($intUSGone>$this->_intReadTimeoutUS){
returnfalse;
}
或者使用內置流處理函數stream_set_timeout()和stream_get_meta_data()處理:
<?php
//Timeoutinseconds $timeout=5; $fp=fsockopen("example.com",80,$errno,$errstr,$timeout); if($fp){ fwrite($fp,"GET/HTTP/1.0rn"); fwrite($fp,"Host:example.comrn"); fwrite($fp,"Connection:Closernrn"); stream_set_blocking($fp,true);//重要,設置為非阻塞模式 stream_set_timeout($fp,$timeout);//設置超時 $info=stream_get_meta_data($fp); while((!feof($fp))&&(!$info['timed_out'])){ $data.=fgets($fp,4096); $info=stream_get_meta_data($fp); ob_flush; flush(); } if($info['timed_out']){ echo"ConnectionTimedOut!"; }else{ echo$data; } } |
file_get_contents超時:
<?php
$timeout=array( 'http'=>array( 'timeout'=>5//設置一個超時時間,單位為秒 ) ); $ctx=stream_context_create($timeout); $text=file_get_contents("http://example.com/",0,$ctx); ?> |
fopen超時:
<?php
$timeout=array( 'http'=>array( 'timeout'=>5//設置一個超時時間,單位為秒 ) ); $ctx=stream_context_create($timeout); if($fp=fopen("http://example.com/","r",false,$ctx)){ while($c=fread($fp,8192)){ echo$c; } fclose($fp); } ?> |
【MySQL】
php中的mysql客戶端都沒有設置超時的選項,mysqli和mysql都沒有,但是libmysql是提供超時選項的,只是我們在php中隱藏了而已。
原文轉自:http://www.kuqin.com/web/20120808/324135.html