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, 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 in the file and line variables. |
Tips and Comments
Comment: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.
Comment:optional file and line The parameter is a new addition in PHP 4.3.
Instance
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 assign them values 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> ... ...