Viewed   107 times

I'm using CURL to get the status of a site, if it's up/down or redirecting to another site. I want to get it as streamlined as possible, but it's not working well.

$ch = curl_init($url);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

return $httpcode;

I have this wrapped in a function. It works fine but performance is not the best because it downloads the whole page, thing in if I remove $output = curl_exec($ch); it returns 0 all the time.

Does anyone know how to make the performance better?



First make sure if the URL is actually valid (a string, not empty, good syntax), this is quick to check server side. For example, doing this first could save a lot of time:

if(!$url || !is_string($url) || ! preg_match('/^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$/i', $url)){
    return false;

Make sure you only fetch the headers, not the body content:

@curl_setopt($ch, CURLOPT_HEADER  , true);  // we want headers
@curl_setopt($ch, CURLOPT_NOBODY  , true);  // we don't need body

For more details on getting the URL status http code I refer to another post I made (it also helps with following redirects):

  • How can I check if a URL exists via PHP?

As a whole:

$url = '';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);    // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true);    // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

echo 'HTTP code: ' . $httpcode;
Sunday, December 4, 2022

Please replace double quotes with single quotes in url,

$url = ''.$city.'/forecasts/latest';
Thursday, September 29, 2022

See also: How to post data in PHP using file_get_contents?

Basically you can use file_get_contents() and stream_context_create() for issuing a POST request. In your case:

$post = http_build_query(array(
    "username" => "user",
    "password" => "pw",
    "example" => "...",

$context = stream_context_create(array("http"=>array(
     "method" => "POST",
     "header" => "Content-Type: application/x-www-form-urlencodedrn" .
                 "Content-Length: ". strlen($post) . "rn",  
     "content" => $post,

$page = file_get_contents("", false, $context);
Sunday, September 18, 2022

I've solved the problem with putting the API key as 'x-api-key' in the HTTP Header.

This looks like the following code:

$api_key = 'abc';
$token = 'xyz';

$authorization = 'Authorization: Bearer ' . $token;
$api = 'x-api-key: ' . $api_key;
curl_setopt($curl, CURLOPT_HTTPHEADER, array($authorization, $api));
Wednesday, September 7, 2022

Just set CURLOPT_HEADER to false.

Monday, October 3, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :