In PHP, the header() function is used to send original HTTP header information, such as redirecting, setting cookies, modifying content types, etc. However, HTTP header information must be sent before any actual output (such as HTML, echo, print, etc.) or an error will be thrown. This is because once the output starts, PHP will automatically send the HTTP header.
To avoid errors when calling header() , we can use the headers_sent() function to detect whether the header has been sent.
headers_sent() is a built-in function provided by PHP to check whether HTTP header information has been sent to the browser. Its basic usage is as follows:
if (!headers_sent()) {
header('Location: https://m66.net/some-page');
exit;
}
If the header has not been sent yet, headers_sent() returns false , indicating that header() can be called safely; if true , it means that the header has been sent, and an error will be reported when calling header() .
headers_sent() can also accept two parameters to get the position (file and line number) of the header output:
if (headers_sent($file, $line)) {
echo "HTTP The head is already there $file The first of the document $line Line send。";
} else {
header('Location: https://m66.net/some-other-page');
exit;
}
This method is especially suitable for debugging and helps you find the location of the code to output in advance.
Before doing a redirect, you should make sure that there is no output:
if (!headers_sent()) {
header('Location: https://m66.net/login');
exit;
} else {
echo "Unable to redirect,Because there is already output。";
}
Similarly, setcookie() relies on HTTP headers, so check it too:
if (!headers_sent()) {
setcookie('user', 'JohnDoe', time() + 3600, '/');
} else {
echo "Unable to set cookie,Because the header has been sent。";
}
If you often encounter header sending errors, consider enabling output buffering at the beginning of the script:
ob_start();
This way all output will enter the buffer first, rather than sending it to the browser immediately until the script is over or the ob_end_flush() is called, giving you more time to send header information safely.