PHP Function Reference

PHP headers_sent() Function



The PHP headers_sent() function checks if or where headers have been sent. Once the header block has been sent, no more header lines can be added using header() function. This function is used to prevent getting HTTP header related error messages.

Syntax

headers_sent(filename, line)

Parameters

hostname Optional. If the filename and line parameters are set, this function will put the PHP source file name and line number where output started in the filename and line variables.
line Optional. Specify the line number where the output started.

Return Value

Returns false if no HTTP headers have already been sent or true otherwise.

Example: headers_sent() example

The example below shows the usage of headers_sent() function. As no header is sent previously, hence !headers_sent() will be TRUE and then header('Location: http://www.example.com/'); will send the header information and as per the header and redirect to the website that is in the parameter.

<?php
//if no headers are sent, send one
if (!headers_sent()) {
  header('Location: http://www.example.com/');
  exit;
}
?>

Example: using filename and line parameters

If the filename and line parameters are set, this function will put the PHP source file name and line number where output started in the filename and line variables.

<?php
//the $filename and $linenum are passed for later use
//do not assign them values beforehand
if (!headers_sent($filename, $line)) {
    header('Location: http://www.example.com/');
    exit;

//triggering an error here
} else {
  echo "Headers already sent in $filename on line $line\n" .
       "Cannot redirect, for now please click this <a " .
       "href=\"http://www.example.com\">link</a> instead\n";
  exit;
}
?>

❮ PHP Network Reference