Cannot modify header information – headers already sent by … | Web Programming Tutorial

Cannot modify header information – headers already sent by …

Published Date: October 13, 2013 |
Published Time: 6:38 pm |

This problem is actually  a  “common problem” which most of the php programmer faces during using sessionand header() function.

This is commonly known as the “whitespace problem”.
The error message typically looks something like
Warning: Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\test\header.php:3) in C:\xampp\htdocs\test\header.php on line 4  (line numbers and file names may vary).

Sometimes there may be two file name and line number like : Cannot modify header information – headers already sent by (output started at C:\xampp\htdocs\test\header.php:3) inC:\xampp\htdocs\test\include\config.php on line 4

This is happened most for extra whitespace or empty line at end of the file.

The fix is, obviously, to remove that whitespace from the file. Read the error message carefully. It says “output started at …” followed by a file name and a line number. That is the file (and line) that you need to edit. Ignore the second file name – that is only a file that included the file that has the whitespace. The first file is the one you have to edit, not the second one.

If it doesn’t work then we will go for another solution.

Another Solution:

If we use header() function for redirect page and  If the header(“Location:example.com”) in a place where some output have already produced means echo someting . Then need to start output_buffering:on in php.ini file

Or we can do it by code and it is more flexible

Write the function at the starting of the page :ob_start();

End in the end of the page: ob_end_flush();

Output Buffering:

Without output buffering (the default), your HTML is sent to the browser in pieces as PHP processes through your script. With output buffering, your HTML is stored in a variable and sent to the browser as one piece at the end of your script.

Advantages of output buffering for Web developers

  • Turning on output buffering alone decreases the amount of time it takes to download and render our HTML because it’s not being sent to the browser in pieces as PHP processes the HTML.
  • All the fancy stuff we can do with PHP strings, we can now do with our whole HTML page as one variable.
  • If you’ve ever encountered the message “Warning: Cannot modify header information – headers already sent by (output)” while setting cookies, you’ll be happy to know that output buffering is your answer.

Leave a Reply

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