PHP Function Reference

PHP get_headers() Function



The PHP get_headers() function returns an array with the headers sent by the server in response to a HTTP request.

Syntax

get_headers(url, associative, context)

Parameters

url Required. Specify the target URL.
associative Optional. If set to true, this function parses the response and sets the array's keys.
context Optional. Specify the context resource created with stream_context_create() function.

Return Value

Returns an indexed or associative array with the headers, or false on failure.

Example: get_headers() example

The example below shows the usage of get_headers() function.

<?php
$url = "https://www.alphacodingskills.com";

//fetching headers
$header = get_headers($url);

//displaying the result
print_r($header);
?>

The output of the above code will be:

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sun, 26 Sep 2021 11:05:07 GMT
    [2] => Server: Apache/2.4.41 (Ubuntu)
    [3] => Set-Cookie: PHPSESSID=v2divqeg27m19balee6mmtmuas; path=/
    [4] => Expires: Thu, 19 Nov 1981 08:52:00 GMT
    [5] => Cache-Control: no-store, no-cache, must-revalidate
    [6] => Pragma: no-cache
    [7] => Vary: Accept-Encoding
    [8] => Connection: close
    [9] => Transfer-Encoding: chunked
    [10] => Content-Type: text/html; charset=UTF-8
)

Example: using associative parameter

If the associative parameter is set to true, the function parses the response and sets the array's keys. Consider the example below:

<?php
$url = "https://www.alphacodingskills.com";

//fetching headers
$header = get_headers($url, true);

//displaying the result
print_r($header);
?>

The output of the above code will be:

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sun, 26 Sep 2021 11:09:57 GMT
    [Server] => Apache/2.4.41 (Ubuntu)
    [Set-Cookie] => PHPSESSID=cbf8hu5i5j0enpth6pg4agifp4; path=/
    [Expires] => Thu, 19 Nov 1981 08:52:00 GMT
    [Cache-Control] => no-store, no-cache, must-revalidate
    [Pragma] => no-cache
    [Vary] => Accept-Encoding
    [Connection] => close
    [Transfer-Encoding] => chunked
    [Content-Type] => text/html; charset=UTF-8
)

❮ PHP URLs Reference