Monday, April 6, 2009

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

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 of  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.

ob_start();

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

ob_end_flush();

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

Refer : http://in.php.net/ob_start & http://in.php.net/ob_flush

7 comments:

Ani said...

thanx for this article.. it's really helpfull.. I've tried some solutions for this problem but never success or left new problems. It took almost two hours.. I think output buffering technique is the best solution.. I've just known bout it.. thanx..

Unknown said...

welcome Riani... by the way are you in same profession?

Ani said...

I'm student of informatics majors.. :)

Anonymous said...

ummm...It does'nt work for me.Can you add me on MSN so that you can help me?I create an uploading script using PHP and has this message come out:
Warning: Cannot modify header information - headers already sent by (output started at /home/grenovid/public_html/uploader/v3/download.php:1) in /home/grenovid/public_html/uploader/v3/download.php on line 1
even though i back-spaced all the extra lines.My email is jian-tin@hotmail.com

ardhi wijayanto said...

thank you, this is solve my problem

killu said...

hi...10X dear...it really helped me.

Anonymous said...

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\... you save me a lot of time man...THANKS SO MUCH