PHP: headers_sent
Check if response headers has already been sent before attempting to send other headers.
553 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
- headers_sent - php.net
Tell us what you think: