PHP Unexpectedly Printing Headers

I worked today on an issue where PHP was unexpectedly printing headers to the browser. I spent a while trying to track this down.

I followed the execution sequence and noticed, by using debug statements and the headers_sent() function in PHP, that headers were printing just after an include statement but there was no print(), echo() or any other reason for the headers to be printed in the include.

In addition, I had a similar debug statement as the last line of the include that told me that no headers were printed. So the execution would return to the file that included the second and before anything else happened, headers were being printed!

It turned out that there was a new line after the ?> in the include file which constitutes output and, therefore, headers were being sent to the browser. The solution was easy, remove the newline character. This made me think, is there a better way to prevent this easy-to-make mistake from happening?

My solution was as follows:

ob_start();
require(somefile.php);
ob_end_clean();

This buffers the output of any require or include until you’re ready to actually output something.

Post a Comment