Thursday, January 24, 2013

PHP Header Problem Solution(Cannot modify header information )

php – Cannot modify header information – headers already sent by (php header already sent error)

This error comes when you print any thing before php header command

PHP handles lots of the work of generating web pages for you, without you even having to ask. A web page is composed of two parts, the header and the body.
When a coder makes a mistake in the manipulation or creation of the headers, this common php error is seen. Here is an example:
Warning: Cannot modify header information – headers already sent by (output started at /home/usr1/public_html/sent.php:42) in /home/usr1/public_html/includes/theme-header.php on line 12
The header is generally stuff that you don’t need to worry about, is generated automatically, and contains information about the page, the server, related cookies. The header information is important, but it is not typically seen by the user. Here is an example:
Example Error Code:
print “text”;
Solution :
function FunJavaScriptRedirection($url)
<script type=”text/javascript”>
window.location = “<?=$url?>”
print “test”;
The header must come first in the response from a web server and is separated from the body by one blank line. The reason this error occurs is that some part of the body of the web page has been sent to the user already when a request is made to set a header value. Because PHP simplifies many things for you, the problem may be hiding in plain site. Here are some guidelines for finding the problem:
1) Find the header() statement that is causing the problem. The error must be at or before this line.
2) Look for any statements that could send output to the user before this header statement. If you find one or more, change your code to move the header statement before them. Complex conditional statements may complicate the issue, but they may also help solve the problem. Consider a conditional expression at the top of the PHP script that determines the header value as early as possible and sets it there.
3) Make sure there is no white space outside of the php start and end tags. While a blank line before the<?php start tag may look innocent, when processed by PHP, it will turn into an echo statement printing out a blank line. This is a common culprit.

No comments:

Post a Comment