Beamtic's logo

Share via:

PHP: headers_list

The headers_list() function will return a list of headers sent by PHP, or headers that are ready to be sent by PHP.


Edited: 2020-08-29 10:46

The headers_list function will returns an array of server response headers; it should not be confused with the reserved variable, $http_response_header — the reserved variable contains the response headers from a HTTP request, while headers_list contains the local response headers set by PHP.

The headers_list function will return raw headers as an indexed array; if instead an associative array with key and value pairs is desired, we can also parse the response headers.

This function will only return the headers that are sent, or ready to be sent, from PHP — not the response headers that are controlled by the web server.

This function will not work from command line scripts.

If calling the headers_list function like this:

header('test: testing');

We will get:

array(1) {
  string(13) "test: testing"

How to parse the headers_list() array

It will often be more useful to create an associative array of key and value pairs when juggling with HTTP headers. To do this, we should parse each header and pick out the key and value using PHP's string functions.

As established in the tutorial on parsing HTTP headers, we can do this very efficiently using the build-in explode function:

$headers = array();
$response_headers = headers_list();
foreach ($response_headers as $value) {
  if(false !== ($matches = explode(':', $value, 2))) {
    $headers["{$matches[0]}"] = trim($matches[1]);


    [test] => testing

Note. We did not attempt to extract the HTTP status code since it is not contained in the array returned to us by headers_list


  1. headers_list -


  1. How to create a custom error handler for PHP that handles non-fetal errors.
  2. We can access other classes properties (variables) and methods (functions) by injecting the class object in the class that needs it.
  3. Setting custom HTTP Headers with cURL is useful when changing User Agent or Cookies. Headers can be changed two ways, both using the curl_setopt function.
  4. Should you use file_get_contnts or cURL when performing HTTP requests from PHP? It does not matter; but regardless of which you use, you should still handle errors properly!
  5. When using file_get_contents to perform HTTP requests, the server response headers is stored in a reserved variable after each successful request; we can iterate over this when we need to access individual response headers.

More in: PHP Tutorials