<- Back

Warning: Cannot modify header information – headers already sent!

warning: headers already sent

Info:
Posted in: Learned along the way
By: Blockcoder ( Admin ) / August 5th, 2011
Stats: 3 responses / Views: 174

Little sympathy

Okay first, i’m not going to explain what causes that warning message, but i’m explaining how to get rid of it. ( Because you don’t want to read so long story. )

Yes, i struggled with that problem for many hours and if I was frustrated with it, you are probably too.


Now, let us focus into the problem:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Your title</title>

  </head>

   <body>

        <?php  header( 'Location: http://www.blockcoders.net' );  ?>

   </body>

<html>

Above, we are sending header information within our php or html code. In this simple example I want browser to take me to the index of blockcoders.net. And after this we are getting this frustrating warning message about header already sent!


Getting rid of it:

We can get rid of it by using ob_start(); and ob_flush(); -php functions. With these we are declaring WHEN we are sending the output buffers.

The warning message says: “headers already sent…” so if we flush output buffer AFTER we use header(); function ( and all of our other possible output data ), it will work:


//make sure HERE is no empty rows or any white space!
<?php ob_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head></head>
<body>

<?php
  header( 'Location: http://www.blockcoders.net' );
?>

</body>
</html>
<?php ob_flush(); ?>

Make sure there are no white spaces at the beginning or at the end of your html or php code!

This was a really simplified example how to kick off the problem. BUT, I’m 100% sure that you won’t get that annoying warning message again!

Thanks folks, hope it helps :)

Leave a Reply

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

*

* Copy this password:

* Type or paste password here:

1,444 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>