2014-09-26 169 views
0

我已經找到一種方式來獲得使用get_headers($url)一個URL的HTTP響應代碼。這個函數返回下面這樣的數組...PHP獲取HTTP響應代碼

Array 
(
    [0] => HTTP/1.1 200 OK 
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT 
    [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux) 
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT 
    [4] => ETag: "3f80f-1b6-3e1cb03b" 
    [5] => Accept-Ranges: bytes 
    [6] => Content-Length: 438 
    [7] => Connection: close 
    [8] => Content-Type: text/html 
) 

我的問題是,我可能,我希望網址循環的大名單,但並獲取每個URL的HTTP響應代碼。這似乎是一個令人討厭和緩慢的方式在循環內部使用這個函數來處理潛在的100個URL。

我如何可以加快這一進程,使之清潔劑或這是做的最好的方法是什麼?我很想知道你的建議。

感謝

+0

你只是想HTTP響應代碼或響應的整個細節? – 2014-09-26 19:10:54

+3

你是否真的對它進行了分析並發現它很慢? – 2014-09-26 19:11:36

+0

只是響應代碼,我知道我可以做一些像'foreach($ url作爲$ url)echo get_headers($ url)[0]; }'。我想知道有什麼更快嗎? – itsliamoco 2014-09-26 19:13:24

回答

0

網絡電話本身需要時間,但可以通過並行運行這些電話去完成得更快。一種方法是使用curl_multi。給我一分鐘,我會寫出一個例子。

//set up list of urls and arrays to hold responses 
$urls = array(
    'http://www.livestrong.com/', 
    'http://www.apple.com/' 
    //add more urls here 
); 

$response_map = array(); 
$responses_by_url = array(); 

//create the multi object 
$multi = curl_multi_init(); 
foreach($urls as $url) { 
    //add a request for each url 
    $ch = curl_init($url); 
    $response_map[$ch] = $url; 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    //since that's all you need, we'll save some bandwidth by just asking for the HEAD 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); 
    curl_multi_add_handle($multi, $ch); 
} 

//start the multi request 
$still_running = 0; 
curl_multi_exec($multi, $still_running); 

//loop while waiting for completion 
do { 
    curl_multi_select($multi); //blocks until state change 
    curl_multi_exec($multi, $still_running); //get new state 

    //read all available new information 
    while ($info = curl_multi_info_read($multi)) { 
     if ($info['msg'] === CURLMSG_DONE) { 
      //we're done, check the result 
      if ($info['result'] === CURLE_OK) { 
       //result ok, parse it 
       $url = $response_map[$info['handle']]; 
       $header_text = curl_multi_getcontent($info['handle']); 
       curl_multi_remove_handle($multi, $info['handle']); 
       $header_array = explode("\r\n", trim($header_text)); 
       $responses_by_url[$url] = $header_array; 
      } else { 
       //record error 
       $responses_by_url[$url] = "error: " . curl_error($ch); 
      } 
     } 
    } 
} while ($still_running); 

//clean up 
curl_multi_close($multi); 

//output results 
var_dump($responses_by_url); 
+0

cURL Multi **不會並行發出請求,它會使它們異步。 – 2014-11-08 07:16:46