Why Does the Header Error Occur?
The PHP Header already sent by output error occurs because data has been sent to the screen, whether it was intentional or not, it happened. First things first, you need to locate where the output is being sent, generally the header error specifies the line where the output occurred, so locating that php file and the line number is probably a good place to start. Tip, on most editors if you do a Ctrl+G you can jump to a line number. Once you locate the line, see if you are either echoing, printing, or you have data outside of the <?php tags in the php file. This will include any white space before the <?php . Here are some examples of code that will cause header errors:
Case 1:
1 2 3 4 | <?php // this will cause a header error due to whitespace before <?php header("Location: somelocation.php"); ?> |
Case 2:
1 2 3 4 5 | <?php echo "Some Output"; // this will also cause an error cause of the echo: set_cookie("name", "value", time()+60); ?> |
Case 3:
1 2 3 4 | <html><?php // this will also cause a header error due to the <html> output session_start(); ?> |
Hopefully you are able to see what is going on in the Cases above. Each one of those (if you create your own PHP file and implement them) should cause a headers already sent error. Now that you know a few examples of how the headers already sent error happens, lets go into Why it happens.
Why Does Outputing Data cause Header Errors?
Probably the easiest way to describe why you are not able to modify headers after output has been sent is simply thinking of the html page as a 3 part system. First you have your header to send, the header data can contain information about the current page, such as it's type, the size, whether to cache the page etc. These are directives to the browser on how to handle the file and display the contents. The header has to be received first before the page will be displayed; however, once the header has been sent / closed you are not allowed to add data to it. The 2nd part would be the body, basically all the html that is being displayed to the end user. Finally the 3rd part could be described as the footer of the document / site. This portion tells the browser that no more data is being sent and to display the page to the user.
Now if you look at your current site (with the exception of AJAX/JavaScript) you will notice that after the page is displayed and fully loaded your PHP script can no longer modify that data without a page refresh. This is due to the body / footer getting closed, in the same manner, once the header has been "closed" you cannot send header calls. I hope I did not confuse you too much there, but think of it like a door, while the door is open you can walk in and out and put stuff inside the room. Once the door is closed you can no longer put items in that room, same principal. Hopefully you now understand why this is happening and now onto the real question, how do you fix the PHP Headers already sent error?
