用curl和php获取http状态代码

时间:2015-11-12 08:50:10

标签: php curl

我试图只获得三位数的http状态代码,而在变量$ response中只有其他内容。例如302,404,301,以及什么不是。我注意到我的代码的另一个观察是在一些网站上,例如谷歌它正在下载似乎是身体的一部分,这是一个巨大的带宽浪费和缓慢。

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

3 个答案:

答案 0 :(得分:9)

您可以将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,""; 
?>

答案 1 :(得分:0)

首先,您只获得标题(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];

答案 2 :(得分:0)

对于状态代码,您可以使用:

Sub Macro1()

Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")

'server authorization (need)
URL = "http://example.com/search.php"
Dim loginData As String
loginData = "login=123&password=123"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
objHTTP.Send loginData


'request
URL = "http://example.com/search.php"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
objHTTP.Send ("var1=value&var2=value&var3=value")

strResponse = objHTTP.responseText
Selection.TypeText Text:= strResponse 

End Sub

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