Beamtic's logo

Share via:

PHP: headers_sent

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

68 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

Comments

  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