Friday, September 11, 2009

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.




0 comments:

Post a Comment

 

About Me

My photo
Hey guys this is Vaseem Ansari, 25 years old, Software & Web Developer, Blogger & works on Open Sources Technologies I love my family and my loved once very much. It takes a while for me to build trust in someone new. I am honest, thoughtful, and my friends tell me that I am wise. I would also say that I am stubborn. but I do learn from my mistakes. I'm Glad I'm Me No one looks The way I do. I have noticed That it's true. No one walks the way I walk. No one talks the way I talk. I am me. There's no one else I'd rather be! Have fun reading this blog and don't forget to subscribe to the feed to keep updated on the latest articles. Visit my Blog at http://www.VaseemAnsari.com/blog/

Followers