Search code examples
phpprogramming-languagesoutput-buffering

php outbuffering and header


I am using php 5.3.6 and below is my code and it is producing an error

Warning: Cannot modify header information - headers already sent by (output started at ............

<?php
ob_implicit_flush(true);

print "<pre>";
$loop = true;
$counter = 0;
while ($loop) {
    $counter++;

    // some code
    print "some output of code. \n";

    if ($elapsedTime > 300) {
        $loop = false;
        print "5 minute passed and loop ended. \n";
    }
}
print "</pre>";

ob_end_flush();

header("refresh:5;url=test.php" );
?>

what I wanted to do is displays contents from each loop while the loop is active. then when the loop is ended I need to flush all the previous output or header and send a new header to refresh the current page.


Solution

  • The short version is, you can't. You can not send headers after the content.

    You could print out a link at the end, that the user can click on to refresh the page. Or if the generation will take a fixed amount of time (say 5 minutes) you could put an HTML meta refresh tag on the page that goes after 5 minutes and 1 second.

    http://en.wikipedia.org/wiki/Meta_refresh

    Header redirects generally take the form Location: ?test.php, if there's a new format that looks just like the meta refresh format, I'm not aware of it, and it would seem to violate how the other headers work (namely key: value). Short version: I don't think that header will work even if it does go first.