PHP headers_sent() Function

Definition and Usage

The headers_sent() function checks whether the HTTP headers have been sent and where they have been sent.

If headers have been sent, it returns true, otherwise it returns false.

Syntax

headers_sent(file,line)
Parameter Description
file,line

Optional.

If set file and line The parameter, headers_sent() will store the name of the PHP source file and line number where the output starts into the file and line variables.

Tips and Comments

Note:Once the header block has been sent, it cannot be used header() Function to send other headers. Using this function can at least avoid error messages related to HTTP headers.

Note:optional file and line The parameter is a new addition in PHP 4.3.

Example

Example 1

<?php
// If headers have not been sent, send one
if (!headers_sent())
  {
  header("Location: http://www.codew3c.com/");
  exit;
  }
?>
<html>
<body>
...
...

Example 2

Use optional file and line parameters:

<?php
// Pass $file and $line for future use
// Do not pre-assign them values
if (!headers_sent($file, $line))
  {
  header("Location: http://www.codew3c.com/");
  exit;
  // Trigger an error here
  }
else
  {
  echo "Headers sent in $file on line $line";
  exit;
  }
?>
<html>
<body>
...
...