How to solve the “Cannot modify header information – headers already sent by…” error in your PHP applications

php-elephant

Today, when I updated a repository in git I realized that my co-workers -accidentally- broke a project (in CakePHP). What error was displaying? simple and a little confusing:

Warning (2): Cannot modify header information - headers already sent by (output started at /app/config/database.php:1) [CORE/cake/libs/controller/controller.php, line 742]

So, for solving this common PHP issue, I recommend use these steps:

1) The first thing is to find a file (or several files) with a blank line at the beginning or at the end of the file. You can read this article for finding a list of files by using a short command: How to find blank lines in a set of files in GNU/Linux or UNIX-Like Operating Systems

2) Be sure that your “pure” PHP files don’t contain a white space or a blank line after CLOSING PHP TAG (?>) or before STARTING PHP TAG (<?php ). In fact, when you create a PHP file (with only PHP source code) it is NOT recommended to use CLOSING PHP TAG (?>). You can read about this in: http://framework.zend.com/manual/1.12/en/coding-standard.php-file-formatting.html (thanks to Daniel Guerrero for sending this link).

3) As you can see -in my case- the error was indicating that the issue was related with a file called database.php in line:1. So, I looked for a blank line or white spaces but no, the file did not have any of these 🙁

4) Last thing that you need to know is about ENCODING, yes when you create or modify a file, some editors save your files in a specific encondig, please read a little more in these links:

When previous steps don’t work, try to find what is the character-encoding used by your PHP file, usually they are in ANSI, or UTF-8 (this second encoding is recommended). So, in my case only was necessary to change the character-encoding to UTF-8 and that solved the problem.

That’s it. Be happy with your project 🙂

Alex Arriaga

Leave a Reply

Your email address will not be published. Required fields are marked *