PHP headers_sent() function

Definition and usage

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

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

Syntax

headers_sent(file,line)
Parameter Description
file,line

Optional.

If set file and line Parameter, headers_sent() will store the name of the PHP source file and line number where the output started in the file and line variables.

Tips and comments

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

Note:optional file and line Parameter is added in PHP 4.3.

ຄວາມຄິດ

ຕົວຢ່າງ 1

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

ຕົວຢ່າງ 2

Use optional file and line parameters:

<?php
// Pass $file and $line for future use
// Do not assign them in advance
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>
...
...