簡體   English   中英

僅使用 curl 和 php 獲取 http 狀態代碼

[英]get ONLY the http status code with curl and php

我試圖只獲取三位數的 http 狀態碼,變量 $response 僅此而已。 例如 302、404、301 等等。 我在代碼中注意到的另一個觀察結果是在某些網站(例如 google)上,它正在下載似乎是身體一部分的內容,這是對帶寬的巨大浪費並且速度很慢。

<?php

$URL  = 'http://www.google.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
$response = curl_exec($curlHandle);
echo $response;  
?>

您可以將CURLOPT_NOBODY選項設置為不接收正文。 然后,您可以使用curl_getinfo獲取狀態代碼。

像這樣:

<?php

$URL  = 'http://www.google.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_NOBODY  , true);  // we don't need body
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_exec($curlHandle);
$response = curl_getinfo($curlHandle, CURLINFO_HTTP_CODE);
curl_close($curlHandle); // Don't forget to close the connection

echo $response,""; 
?>

首先,您只獲得標題(CURLOPT_NOBODY)。

然后捕獲HTML作為結果(CURLOPT_RETURNTRANSFER)。

最后,您使用正則表達式提取HTTP代碼,該正則表達式獲取由空格包圍的第一個數字。

$URL  = 'http://www.google.com';
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $URL);
curl_setopt($curlHandle, CURLOPT_NOBODY, true);
curl_setopt($curlHandle, CURLOPT_HEADER, true);
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curlHandle);
preg_match('/ \d+ /', $response, $matches);
$response = $matches[0];

對於狀態代碼,您可以使用:

function getStatusCode($url) {
   $headers = get_headers($url);
   preg_match('/\s(\d+)\s/', $headers[0], $matches);
   return $matches[0];
 }

 echo getStatusCode('http://www.google.com');

http://php.net/manual/en/function.get-headers.php

curl_exec($curlHandle);
$curl_info = curl_getinfo($curlHandle);
$response =  $curl_info['http_code'];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM