Cannot modify header information – headers already sent.

This is one of the most common PHP errors that you will come across:

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

This error is telling you that you cannot print data before you modify header information.

Take the following example:

//Example output using echo.
echo 'Example';

//Attempt to redirect.
header('Location: index.php');

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

The common causes of this warning are as follows:

  1. Attempting to modify header information after the output has already been sent to the client (as seen in the example above).
  2. Whitespace and newline characters that exist above the opening PHP tag (<?php).
  3. Whitespace after the closing PHP tag (?>) in a file that has been included at the top of the script.
  4. Other PHP errors and warnings that have been printed out before the headers are modified.
  5. Attempting to modify header information after your HTML has already been displayed.

Below is an example of whitespace causing the “headers already sent” error:

 <?php
header('Location: index.php');

As you can see, there is a space before our opening PHP tag. This space is interpreted as output by the server.

HTML can also cause this warning:

<h1>Example</h1>
<?php
header('Location: test.php');

In this case, the HTML is being sent to the browser before our redirect statement.

Fixing PHP’s “headers already sent” error.

To fix this issue, you will need to understand PHP’s warning messages.

Let’s take a look at 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

In this case, PHP is telling us that LINE 12 in my-page.php is causing the issue. It is also telling us that our attempt to modify the header information failed on LINE 67.

Basically, the output on LINE 12 prevented us from modifying the header information on LINE 67.

Modifying Header Info.

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