PHP Error - Warning: Cannot modify header information - headers already sent by …

The Problem:

When you load up the PHP script you just created, you get the following error message:

“Warning: Cannot modify header information - headers already sent by …”

Which is then followed by a file location and line number where the output started, and the file and line number where the error occured (the function call where the header was trying to be sent).

The functions that send HTTP headers that can cause this problem are header() and setcookie().

The Explanation:

This problem occurs when you are trying to send HTTP header information AFTER output to the browser has already been started. The most common occurrence of this error is when you have some code that looks something like the following:

<html>
<head>
<title>My Webpage</title>
</head>
<body>
<?php
if(!$loggedIn) {
    header("Location: http://www.mysite.com/login.php");
} else {
    // ...
}
?>
...

In this case, because the script has already sent output to the browser (content before the PHP tags), the HTTP headers have already been finalized and sent. When you try to send another header after the headers have already been sent, you receive the error message that they were already sent, and the redirection fails.

The Solution:

The solution to this problem is simply to move the function call that sends the headers to send them before any output has been sent to the brower. So using the example with the above code, your new code would look like this:

<?php
if(!$loggedIn) {
    header("Location: http://www.mysite.com/login.php");
} else {
    // ...
}
?>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
...

The only change here was we moved the PHP code block from below the HTML code to above the HTML code. In most cases, your code will not be as clear as the code sample above where you can do a simple cut & paste to the top of the file and have everything working. Most times there are multiple include files and you will have to do a good bit of code adjustment to get things working right. The key to solving this problem is just to remember that no content can precede a call to the header() or setcookie() functions - not even one whitespace character before your opening PHP tag.

Tags: ,

Leave a Reply

You must be logged in to post a comment.