2012-02-07 65 views
0

這怎麼能在PHP做到這一點捲曲在PHP

curl -I http://www.google.com | grep "Server:" 

來完成,並有可能只是回聲操作系統,如Linux或站點的窗戶,像Web服務器是呼應使用curl

我嘗試

<? 
$ch = curl_init(); 
curl_setopt ($ch, CURLOPT_URL,"http://google.com"); 
curl_setopt ($ch, CURLOPT_HEADER, 1); 
$data = curl_exec ($ch); 
curl_close ($ch); 
echo $data ; 

?> 
+1

您是否試過閱讀[PHP cURL文檔](http://php.net/manual/en/book.curl.php)或[PHP模式匹配文檔](http://php.net/manual /en/function.preg-match.php)? – Leigh 2012-02-07 11:14:52

+0

我無法真正弄清楚這就是爲什麼我來到這裏@Leigh – 2012-02-07 11:22:59

+0

至少告訴我們你的嘗試。 – Leigh 2012-02-07 11:24:12

回答

0
<?php 
// create a new cURL resource                                 
$ch = curl_init(); 

// set URL and other appropriate options                              
curl_setopt($ch, CURLOPT_URL, "http://www.google.com/"); 
curl_setopt($ch, CURLOPT_HEADER, true); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

// grab URL and pass it to the browser                              
$result = curl_exec($ch); 

/* Curl returns multiple headers, if the last action required multiple                      
* requests, e.g. when doing Digest authentication. Only parse the                       
* headers of the latest response. */ 
preg_match_all('/(^|\r\n\r\n)(HTTP\/)/', $result, $matches, PREG_OFFSET_CAPTURE); 
$startOfHeaders = $matches[2][count($matches[2]) - 1][1]; 
$endOfHeaders = strpos($result, "\r\n\r\n", $startOfHeaders); 
$headers = substr($result, $startOfHeaders, $endOfHeaders - $startOfHeaders); 
$headers = preg_split("/\r?\n/", $headers); 
foreach ($headers as $headerLine) { 
    if (preg_match('|^Server:\s+(.+)|', $headerLine, $m)) { 
    var_dump($m[1]); 
    } 
} 

// close cURL resource, and free up system resources                           
curl_close($ch); 

基本上這是從the Horde_Http library的提取物。特別是the Curl requestthe Curl response處理程序。

它比您對「grep」命令所做的更復雜一些,但看起來好像您要分析響應頭。這就是爲什麼我在代碼中留下更復雜的標題分析的原因。

+0

是的,這就是我要找的:)謝謝! – 2012-02-07 11:34:48

+0

關於我提到的第二個問題,你可以說些什麼? – 2012-02-07 11:36:33

+0

識別操作系統並不可靠。但是通常Web服務器的默認設置將允許您提取操作系統。請參閱[鏈接](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.38) – 2012-02-07 12:03:04