vijayjoshi.org - php | javascript | ajax | and all things web

FAQ: How to fix php warning – “Cannot modify header information – headers already sent”

You must have seen this error message quite a lot of times.

Cannot modify header information – headers already sent

The following code sample will throw the same error:

//this will result in header error
<html>
<head><head>
<body>
<?php
header("Location:http://www.google.com");
?>
</body>
</html>
<?php ob_end_flush(); ?>

Outputting any html to browser before calling functions like session_start, header or any such function which sends http headers to the browser result in this error. This is because php does not wait for whole page to be generated, rather it renders the page in a linear fashion.Therefore sending any html/data before the http headers have been sent results in an error.

But do not worry.There is a workaround for this error.

  1. Turn the output buffering on.
  2. Let the whole script execute and collect generated data in its buffer.
  3. Output all data to the browser.

Php has output control functions which can be used for this purpose.

At the very start of your script put this line:

<?php  ob_start(); ?>

This will turn output buffering on. After this write whatever code you want. When you are done append another line in the end.

// this will not give the header error
<?php ob_end_flush(); ?>

The code now becomes:

<?php  ob_start(); ?>
<html>
<head>
<head>
<body>
<?php
header("Location:http://www.google.com");
?>
</body>
</html>
<?php ob_end_flush(); ?>

ob_start turns output buffering on as a result of which no data or headers are sent to the browser. Instead, all data is collected in internal buffer. Calling the function ob_end_flush dumps all the buffer data to the browser.

Related Posts

Posted in : FAQ, PHP
Tags:

1 Comment to “FAQ: How to fix php warning – “Cannot modify header information – headers already sent””

Add Comments (+)

  1. ibe says:

    this was very helpful to me. i have trying a way to fix this bug in php header in my script no solution.

    but this one: ob_start(); this is the killer and am so happy i found it

    thank you Vijay

Leave a Reply

Leave a Reply

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

*

* Copy this password:

* Type or paste password here:

57,054 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>