php獲取http頭部請求狀態資訊
阿新 • • 發佈:2018-12-31
我們在使用站長工具會發現有一個獲取網站http狀態資訊了,其實這個功能使用php非常的簡單的,我們可以使用curl來實現下面來看一些整理的例子。使用curl需要在php.ini中設定啟用才行 >< Windows的伺服器中,開啟php.ini,找到:extension=php_curl.dll去掉前面的註釋既可 。實現程式碼如下:
或者直接使用get_headers函式get_headers — 取得伺服器響應一個 HTTP 請求所傳送的所有標頭例子
程式碼如下 | 複製程式碼 |
$curl = curl_init(); $url=’http://www.111cn.net’; curl_setopt($curl, CURLOPT_URL, $url); //設定URL curl_setopt($curl, CURLOPT_HEADER, 1); //獲取Header curl_setopt($curl,CURLOPT_NOBODY,true); //Body就不要了吧,我們只是需要Head curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); //資料存到成字串吧,別給我直接輸出到螢幕了 $data = curl_exec($curl); //開始執行啦~ echo curl_getinfo($curl,CURLINFO_HTTP_CODE); //我知道HTTPSTAT碼哦~ curl_close($curl); //用完記得關掉他 |
程式碼如下 | 複製程式碼 |
<?php if(!function_exists('get_headers')){ function get_headers($url,$format=0){ $url=parse_url($url); $end="\r\n\r\n"; $fp=fsockopen($url['host'],(empty($url['port'])?80:$url['port']),$errno,$errstr,30); if($fp){ $out="GET / HTTP/1.1\r\n"; $out.="Host: ".$url['host']."\r\n"; $out.="Connection: Close\r\n\r\n"; $var=''; fwrite($fp,$out); while(!feof($fp)){ $var.=fgets($fp,1280); if(strpos($var,$end)) break; } fclose($fp); $var=preg_replace("/\r\n\r\n.*\$/",'',$var); $var=explode("\r\n",$var); if($format){ foreach($var as $i){ if(preg_match('/^([a-zA-Z -]+): +(.*)$/',$i,$parts)) $v[$parts[1]]=$parts[2]; } return $v; }else{ return $var; } } } } echo '<pre>'; print_r(get_headers('http://www.111cn.net')); |