Headers already sent by..

Sunday, June 17, 2007

Familiar with that ?

For some PHP newbies that warning is quite irritating. This an example of script that generate that warning.

<?php
echo "some output here";
header("location: index.php");
?>
Means, there should be on output before the tag header("location: index.php") or the warning will show up. The warning will tell you something like "Cannot modify header information - headers already sent by ....". You have to make sure that no output is made before the header tag. In this case, you have to remove the echo "some output" to make the script works and redirected user to index.php. The other solution if using ob_start() and ob_end_flush(), ob_start() buffers your whole page before load it, so the output will not be load until WHOLE page is buffered. Thus, your script will work and user will redirected to index.php.
<?php
ob_start();
echo "some useless output here";
header("location: index.php");
ob_end_flush();
?>
Or, you could use meta instead of header. Meta is not part of PHP you could use it on plain HTML. Here's how
<?php
echo "some output here";
?>
<meta http-equiv="refresh" content="0;url=index.php">
Using meta, u can make a kind ot imer by modifying the number on content, the above example using content="0... " to diretly redirected user to index.php. You can however, change the value to something like 10, 5, to redirect the user AFTER that many second(s). Cheers.

0 comments: