Cannot Modify Header Information Error
What's a Header and What's Wrong With It?
No this isn't a soccer tutorial. We are talking about a common error in PHP scripts. The header we are talking about is a piece of data that precedes a larger chunk and carries information about how to handle the larger chunk of data. Note that this "header information" must precede the actual data. An example would be the header of any file on your computer. There is a chunk of data attached to the top of almost every file that tells your operating system and programs about that file.
This is true for web pages also. The program that needs the header information is your browser. It needs the information first so it knows how to handle the HTML it will receive from the server. PHP knows this and will send the header information automatically before any HTML.
So what's the problem? PHP has a function called header(); that allows PHP scripts to add or change the header information before it is sent to the browser. What would happen, then, if we did something like the code below?
<?php
echo "This is a bunch of HTML!";
header("Location:http://www.hostingfanatic.com");
?>
The answer to that is the amazing Warning: Cannot modify header information - headers already sent warning. This is because PHP has already sent the header information before it executed the first line of the code. You can't alter the header information if it has already been sent out.
Other functions that can cause this error are usually session or cookie related. As an example a call to session_start() or a call to setcookie(), if there is any output beforehand, will cause the infamous error also.
While the cause of this error is usually fairly easy to track down once you know what it is all about, there are times when it can get tricky. One very common mistake happens when using PHP includes(). As an example let's say that the first line in the code above was an include() instead of an echo() statement. Obviously, if the include contains any output whatsoever you are going to get the really neat warning about the headers already being sent.
What if there were just a single space before the opening PHP tag in the code above? This is where it sometimes gets tricky. PHP will send the headers for that one little space as it is actually HTML. You will still get Warning: Cannot modify header information - headers already sent. Note that this will also happen if the one little space is in the include. If it is output and it comes before the header() statement then you will always have the priviledge of enjoying that wonderful PHP warning.
I hope this steared someone in the right direction. I will be constantly adding stuff like this to HostingFanatic. Keep checking back. If you want to support the site then consider us a resource for searching for web hosting and internet service providers.
Blink
Del.icio.us
Digg
Furl
Google
Simpy
Spurl
Y! MyWeb
