What is the “headers already sent” PHP error?
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 (
<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
Just because you cannot see anything does not mean that PHP sees the same.
- Download the file mentioned in the error message via FTP or the file manager provided in your control panel.
- Open the file in a plain text editor (notepad or similar is the recommended).
- Ensure that the first characters are
- Ensure that the last characters are either NOT a PHP closing tag or a closing tag
?>with no blank lines or spaces after it.
- 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:
- Place the cursor between the ? and >
- 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.
- Keep that key pressed
- For at least 15 seconds
- Now type > and
- save without pressing any other key at all.
- If you press another key, you will bring the problem back.
- DO NOT PUT CODE IN UNNECESSARY CODE BLOCKS, PUT THEM IN A SINGLE PHP BLOCK.