Current Location: Home> Latest Articles> Use headers_sent() to check whether the header can be set

Use headers_sent() to check whether the header can be set

M66 2025-05-17

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.

What is headers_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() .

Check the specific sending location

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.

Common Scenes

1?? Page redirection

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。";
}

2?? Set cookies

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。";
}

Tips: Turn on output buffering

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.