-1

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.

hakre
  • 193,403
  • 52
  • 435
  • 836
Prakash
  • 2,749
  • 4
  • 33
  • 43

2 Answers2

1

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.

preinheimer
  • 3,712
  • 20
  • 34
0

As suggested by preinheimer the header must be sended before each page ouput. Without using the headers you can use one row of javascript code for a simple redirect. This may be a solution for you:

<?php

    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>";

    # The php code has ended and the javascript code is ready for redirecting... (external to php tags)
?>
<script type="text/javascript">
    window.location="http://www.example.com/";
</script>
bitfox
  • 2,281
  • 1
  • 18
  • 17