Contact for Expert ServicesAdvertise with Ecomspark.

Warning: Cannot modify header information – headers already sent by ERROR

This error message we usually see, while doing php programming. Lets find out the main cause why this warning message occurs.

A web page consists two parts header and body. Some times when a programmer do mistake unintentionally then see such php errors

Warning: Cannot modify header information - headers already sent by (output started at /some/file.php:12) in /some/file.php on line 23

This error comes when anything is sent before you send http header request. In simple words header should be sent before any body output.

<?php
echo "Hello Gaurav"; // body
// other out put
header("Location:httop://......"); //header
?>

Above header should be sent before body output.

warning-can-not-modify-header

Sample http response –

HTTP/1.1200 OK

Powered-By: PHP/5.3.7 Vary:Accept-Encoding Content-Type: text/html; charset=utf-8

<html><head><title>PHP page output page</title></head><body><h1>Content</h1> <p>Some more output follows...</p>

Php scripts generates html output and also pass header to the webserver. It has to pass header first before the output. When php send output(echo , print or html ) first then such error comes. You can find the error line in header warning itself.
Some other reasons are white space often at beginning and end of php tag.
<?php
…..
?>
See the space before beginning php tag. Always take care such simple things to avoid such mistakes.

The problem is that many editors seem to add additional blanks (spaces) and/or empty lines at the end of a file when you edit it. This so-called whitespace is then sent to the browser when the file is loaded and interferes with the header of a page.

There is another way –

Add <?php ob_start();  ?> at the top of page. and <?php  ob_flush(); ?> at the end of code.

ob_start() – Its turning on the output buffer. So any output is kept in the buffer. And ob_flush() is to flush the buffer

 

 

 

 

3 Comments

Add a Comment

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

Translate »