While using PHP, you might have faced the following warning while using the header functions like header(), setcookie().
Warning: Cannot add header information – headers already sent by (output started at file.php:[line_number])
Reason Behind the warning:
You’ve already sent output to the browser and after that using the header functions in the code causes this warning to occur. Let’s look at the following example
<?php echo "output already sent here"; header("Location: http://roshanbh.com.np"); ?>
In the above example, output is already sent to browser before the header function is used and it is the main reason behind this warning.
1) As far as possible, Don’t send output to the browser before any header function.
2) If you have to send the output to the browser before using header function then put ob_start() function at the top of the page. This function turns output buffering on and hence solve the problem. And if you want to turn off the output buffering then you can use ob_end_flush() at the end of the page. But PHP automatically turn off the output buffering you don’t need to do this explicitly.