home ~ previous

PHP

Warning: Cannot modify header information - headers already sent by...

Lovely. There you are all nice and happy. You are forwarding from one page to another using:

1
2
3
<?php
    header('Location: http://www.example.com/');
?> 

And you are presented with this error:

Warning: Cannot modify header information - headers already sent by...

Usually, this is because you have some HTML already declared or worse still, a sneaky bit of whitespace has been added somewhere it shouldn't.

Sometimes the error is declared and you can't find the cause.

This code snippet will sort the issue.

You go to the offending page, place the first line at the top of the page and the second at the bottom of the page. Your code is then in the middle of these two lines.

Ultimately, you should make sure that there is no HTML before the headers are sent. But if all else fails, this code will see you good.

1
2
3
4
5
6
7
<?php
    ob_start();
   
    ### your code here

    ob_end_flush();
?>     

This function will turn the output buffering on. While this is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer... and this sorts it. You can read more here

home ~ previous

Rohan Leach .... thoughtful