Apr 13, 2020 6:30 AM

Getting HTTP code in PHP using cURL

Getting HTTP code in PHP using cURL

In this article I will give an example of how to get HTTP code in PHP using cURL. You can check if the site is accessible and what status code the server returns. You can also find out if the server is redirecting you to another URL and determine what the last URL will be.

function getHttpCode($url, $followLocation = false, $maxRedirects = 10, &$lastUrl = '')
{
    // Options
    $curlOptions = [
        CURLOPT_HEADER => true,
        CURLOPT_NOBODY => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_CONNECTTIMEOUT => 10,
    ];

    if ($followLocation) {
        $curlOptions[CURLOPT_FOLLOWLOCATION] = true;
        $curlOptions[CURLOPT_MAXREDIRS] = $maxRedirects;
    }

    // Initialization
    $ch = curl_init($url);

    // Set options
    curl_setopt_array($ch, $curlOptions);

    // Execute request
    curl_exec($ch);

    // Get HTTP code
    $result = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // Get last URL
    $lastUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    // Close the resource
    curl_close($ch);

    return (int) $result;
}

Let's check getting the HTTP code (expected result — 200):

print_r(getHttpCode('https://www.google.com'));

/**
[output]
200
 */

Now consider the redirection case (expected result — 302):

print_r(getHttpCode('https://maps.google.com'));

/**
[output]
302
 */

You must set the $followLocation = true parameter to determine the last URL. You can also specify the maximum number of redirects using the $maxRedirects parameter. Let's determine the last URL from the previous example:

getHttpCode('https://maps.google.com', true, 10, $lastUrl);
print_r($lastUrl);

/**
[output]
https://www.google.com/maps?hl=en
 */

Other articles