KNOWNHOST KNOWLEDGE BASE

Hosting Question? Find the Solution - Browse our Guides, Articles, and How-To's

What is the “headers already sent” PHP error?

Category: Common Issues
Tags: # # #

A common error seen, however rarely known or understood is the “headers already sent” error. Which may look similar to this:

  Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23

Why does it happen?

To understand why headers must be sent before output it’s necessary to look at a typical HTTP response. PHP scripts mainly generate HTML content, but also pass a set of HTTP/CGI headers to the webserver:

  HTTP/1.1200 OK
  Powered-By: PHP/5.3.7Vary:Accept-EncodingContent-Type: text/html; charset=utf-8<html><head><title>PHP page output page</title></head><body><h1>Content</h1> <p>Some more output follows...</p>and<a href="/"><img src=about:note>...

The page/output always follows the headers. PHP is required to pass the headers to the web server first. It can only do that once. And after the double linebreak, it can’t ever append to them again.

When PHP receives the first output (printecho<html>) it will “flush” the collected headers. Afterward, it can send all the output bits it wants. But sending further headers is impossible from then.

Functions that modify the HTTP header

  • header
  • header_remove
  • session_start
  • session_regenerate_id
  • setcookie
  • setrawcookie

Possible solution

Just because you cannot see anything does not mean that PHP sees the same.

  1. Download the file mentioned in the error message via FTP or the file manager provided in your control panel.
  2. Open the file in a plain text editor (notepad or similar is the recommended).
  3. Ensure that the first characters are <?php
  4. Ensure that the last characters are either NOT a PHP closing tag or a closing tag ?> with no blank lines or spaces after it.
  5. Before saving, or use the Save as dialog, ensure the file encoding is anything without the ‘BOM’ suffix.

To be sure about the end of the file, do this:

  1. Place the cursor between the ? and >
  2. Now press the DELETE key on your computer
    • Note to MAC users: The “DELETE” key on a PC deletes characters to the right of the cursor. That is the key noted here.
  3. Keep that key pressed
  4. For at least 15 seconds
  5. Now type > and
  6. save without pressing any other key at all.
  7. If you press another key, you will bring the problem back.
  8. DO NOT PUT CODE IN UNNECESSARY CODE BLOCKS, PUT THEM IN A SINGLE PHP BLOCK.

Referenced and helpful resources