You must have seen this error message quite a lot of times.
Cannot modify header information – headers already sent
The following code sample will throw the same error:
//this will result in header error
<html>
<head><head>
<body>
<?php
header("Location:http://www.google.com");
?>
</body>
</html>
<?php ob_end_flush(); ?>
Outputting any html to browser before calling functions like session_start, header or any such function which sends http headers to the browser result in this error. This is because php does not wait for whole page to be generated, rather it renders the page in a linear fashion.Therefore sending any html/data before the http headers have been sent results in an error.
But do not worry.There is a workaround for this error.
- Turn the output buffering on.
- Let the whole script execute and collect generated data in its buffer.
- Output all data to the browser.
Php has output control functions which can be used for this purpose.
At the very start of your script put this line:
<?php ob_start(); ?>
This will turn output buffering on. After this write whatever code you want. When you are done append another line in the end.
// this will not give the header error
<?php ob_end_flush(); ?>
The code now becomes:
<?php ob_start(); ?>
<html>
<head>
<head>
<body>
<?php
header("Location:http://www.google.com");
?>
</body>
</html>
<?php ob_end_flush(); ?>
ob_start turns output buffering on as a result of which no data or headers are sent to the browser. Instead, all data is collected in
internal buffer. Calling the function ob_end_flush dumps all the buffer data to the browser.
0 comments:
Post a Comment