PHP: headers_sent

Check if response headers has already been sent before attempting to send other headers.

553 views

Edited: 2020-09-15 09:04

The headers_sent function checks whether HTTP response headers has been sent earlier in a PHP-based web application.

headers_sent returns true when headers has already been sent, and false otherwise.

The function can be used like this:

if (true === headers_sent()) {
  echo 'Headers has already been sent';
  exit();
}

The headers_sent function also makes it possible to return the line number and filename where the headers are being sent; to do this, we may use the optional line and file parameters:

if (true === headers_sent($file_name, $line_number)) {
  echo 'Headers already sent in file: ' . $file_name . ' at line number: ' . $line_number;
  exit();
}

List of headers sent by PHP

We can use the headers_list function to return a list of headers that has been sent, or is about to be sent, although this will only return headers controlled by the PHP script.

header('test: testing');
var_dump(headers_list());

Result:

array(1) {
  [0]=>
  string(13) "test: testing"
}

Links

  1. headers_sent - php.net

Tell us what you think:

  1. In this Tutorial, it is shown how to redirect all HTTP requests to a index.php file using htaccess or Apache configuration files.
  2. How to create a router in PHP to handle different request types, paths, and request parameters.
  3. Tutorial on how to use proxy servers with cURL and PHP
  4. 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.
  5. How to effectively use variables within strings to insert bits of data where needed.

More in: PHP Tutorials