4

I'm trying to get only the three digit http status code number and nothing more in the variable $response. For example 302, 404, 301, and what not. Another observation I noticed with my code is on some websites such as google it's downloading what appears to be part of the body, which is a huge waste of bandwidth and slow.

<?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 Answers 3

16

You can set the CURLOPT_NOBODY option to not receive a body. Then you can get the status code with curl_getinfo.

Like so:

<?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,""; 
?>
Sign up to request clarification or add additional context in comments.

Comments

0

First off, you get only the headers (CURLOPT_NOBODY).

Then you capture the HTML as the result (CURLOPT_RETURNTRANSFER).

Finally you extract the HTTP code with a regex that gets the first numbers surrounded by spaces.

$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];

Comments

0

For just the status code you can use this:

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

7 Comments

I get a beautiful warning when trying to use get_headers function. Why do you think it might be?
@Amarnasan What does the warning say?
Nothing else? With $url = 'google.com'? But the status code is still returned?
Nothing else, and I got no status code at all. Even if I skip the error with "@", I get nothing.
@Amarnasan Ok, I found also this example: php.net/manual/en/function.get-headers.php#97684 I'm sorry, I can't help you with no more error details.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.