Tuesday, July 17, 2012

Cannot modify header information - headers already sent.


When ever we are dealing with header function the common warnning we get is "Cannot modify header information - headers already sent". 

Lets see php.net mannual -"header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called."  So as it clearly indicate that if our code is generating a space or empty lines also result into this warnning. 

Now the solution: A solution for this is dont allow any output to print any thing on browser till all headers are executed. So we are adding ob_start() in the begnning of page & ob_flush() at the end of page. then what ever is the output will be there in the output buffer, So this time we can use header function without any worry. And your code will somthing like:

<?php
ob_start();
//Your code
header('Location: example.php');
exit()
//your code
ob_flush();
?>
In case we are dealing with session, then session should start after ob_start() otherwise again it will through same warnning.