Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get ONLY the http status code with curl and php

Tags:

php

curl

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;  
?>
like image 467
michelle Avatar asked Sep 05 '25 11:09

michelle


1 Answers

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,""; 
?>
like image 151
Jerodev Avatar answered Sep 09 '25 20:09

Jerodev