Saturday, April 4, 2009

PHP Warning: Cannot modify header information - headers already sent by (output ...)


Share at Facebook

Error Message from your Apache while browsing PHP page.
PHP Warning: Cannot modify header information - headers already sent by (output ...)

There can be only one reason for this kind of error.

Possibly you are trying to change the header of the page. But, you might have printed something before changing the header. For example the below code will give the error to you.


//See you output to browser before printing header
echo "hello... php...";
// printing your header
header("Location: index.php");


There are lots of hosting where you'll not see this kinds of error. Cause probably they have some configuration to handle this issue. But still its a good practice to not follow dirty coding like above.

Not only the Location header, it can be anything. What you can do, if you are sure, then just print all the headers at the top of the php script. This will help you to avoid the error. For example

// printing your header
header("Location: index.php");
//See you output to browser is after printing header
echo "hello... php...";

But the problem is, there can be lots if if and else conditions inside your php script. Depending upon the if else blocks, you need to change the http headers. That case above solution won't work. What you can do is, just use the output buffering technique.

Put the below code at the top of your PHP script to start the output buffering.

<?php ob_start(); ?>

And but the below code at the bottom of the php script to flush the buffer.

<?php ob_flush(); ?>

This way, whatever you are doing inside your php script, won't see this kind of weird error again.




No comments: