Cannot modify header information – headers already sent.

This is probably one of the most common PHP errors that you will come across as you struggle to come to grips with the intricate world of web development:

Cannot modify header information – headers already sent in (file location).

To sum this error up – It is basically telling you that you cannot output data before you attempt to modify header information. A quick example:

The code above will cause the error in question, simply because we attempted to change our header information after we had already printed out the string “Example” to the browser.

Common causes of this particular error are as follows:

  1. Attempting to modify header information after output has already been sent to the client (as seen in the code example above).
  2. Random whitespace and newline characters above the opening PHP tag.
  3. Whitespace after closing PHP tags in files that have been included at the top of the script.
  4. PHP errors causing error messages to be printed out onto the screen before the headers are modified.
  5. Attempting to modify header information after HTML has already been displayed.

An example of whitespace causing the “headers already sent” error:

Here, we can see that there is a blank line before our opening PHP tag. This blank line is interpreted as output by the server, resulting in the “headers already sent” error.

An example of HTML causing issues:

Our HTML is interpreted as being output, which prevents us from carrying out the intended redirect.

Debugging.

To debug this issue, you need to learn how to understand the warning message that PHP displays. Lets take the following example:

Warning: Cannot modify header information – headers already sent by (output started at /www/my-page.php:12) in /www/my-page.php on line 67

Here, we can see that PHP is telling us what the problem is being caused by LINE 12 in my-page.php. It is also telling us that our attempt to modify the header information failed on LINE 67 on my-page.php

Basically, the output on LINE 12 prevented our attempt to modify the header information on LINE 67.

Modifying Header Info.

There are a number of PHP functions that allow us to modify the HTTP header that the client receives. Popular examples include the functions header, session_start and setcookie. When using these functions, you MUST make sure that no output has been sent to the client beforehand.

Facebook Comments