php擷取http頭部請求狀態資訊

來源:互聯網
上載者:User

使用curl需要在php.ini中設定啟用才行 >< Windows的伺服器中,開啟php.ini,找到:

extension=php_curl.dll

去掉前面的注釋既可 。

實現代碼如下:

 代碼如下 複製代碼

$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); //用完記得關掉他

或者直接使用get_headers函數

get_headers — 取得伺服器響應一個 HTTP 要求所發送的所有標題

例子

 代碼如下 複製代碼

<?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'));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.