PHP – Get HTTP Response Status Code From a URL

This post shows you how to get the HTTP response status code from a URL. To do this, we will use get_headers built-in function, which returns an array with the headers in the HTTP response.


1. Exploring get_headers function

Let’s create a test to check what response headers we will get.

$url = '';
$responseHeaders = get_headers($url, 1);

And here is the result:

    [0] => HTTP/1.0 200 OK
    [Content-Type] => text/html; charset=UTF-8
    [Link] => ; rel=""
    [Date] => Tue, 19 Jun 2018 07:42:10 GMT
    [Accept-Ranges] => bytes
    [Server] => LiteSpeed
    [Alt-Svc] => quic=":443"; ma=2592000; v="35,37,38,39"
    [Connection] => close

As you can see in the result, the HTTP response status code is in the first index value of the array (HTTP/1.0 200 OK).

The response status code can be:

  • HTTP/1.0 200 OK:
  • HTTP/1.0 301 Moved Permanently
  • HTTP/1.0 400 Bad Request
  • HTTP/1.0 404 Not Found
  • ect.

You can find the full list of response status code on this page.


2. Implementation

function getHTTPResponseStatusCode($url)
    $status = null;

    $headers = @get_headers($url, 1);
    if (is_array($headers)) {
        $status = substr($headers[0], 9);

    return $status;

In the above code, we have implemented the function that returns an HTTP response status code only from given URL, i.e. we have removed HTTP/1.0 string in the first index value of the array.

3. Usage

The below are two examples showing how to use the implemented function.

  • Example 1:
$url = '';
$statusCode = getHTTPResponseStatusCode($url);
echo $statusCode;
  • Output 1:
200 OK


  • Example 2:
$url = '';
$statusCode = getHTTPResponseStatusCode($url);
echo $statusCode;
  • Output 2:
404 Not Found

Leave a Reply

1 Comment threads
0 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Charles Recent comment authors
newest oldest most voted

Thank for sharing this post with us. Very helpful and useful information.