Solving ‘Warning: Cannot add header information’ in PHP

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.

Solution :

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.

3 thoughts on “Solving ‘Warning: Cannot add header information’ in PHP

  1. One thing to watch for when using output buffering is how much data your actually printing.

    If you’re outputting something large (For example, a file for a download), then you may run into memory problems. I’ve seen this on a few php scripts used for downloads, and it causes corrupted downloads.

    So if you know you will be outputting a lot (several megabytes), of data, it’s probably best to stay away from output buffering.

  2. yes i totally agree with you…..

Leave a Reply

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

*

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=""> <s> <strike> <strong>