-1

我正在使用 php 5.3.6 以下是我的代码,它正在产生错误

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

我想做的是在循环处于活动状态时显示每个循环的内容。然后当循环结束时,我需要刷新所有先前的输出或标题并发送一个新标题以刷新当前页面。

4

2 回答 2

1

简短的版本是,你不能。您不能在内容之后发送标题。

您可以在最后打印出一个链接,用户可以单击该链接来刷新页面。或者,如果生成需要固定的时间(比如 5 分钟),您可以在 5 分 1 秒后的页面上放置一个 HTML 元刷新标记。

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

标头重定向通常采用这种形式Location: ?test.php,如果有一种看起来像元刷新格式的新格式,我不知道,它似乎违反了其他标头的工作方式(即键:值)。简短版本:我认为即使它先行,标题也不会起作用。

于 2011-06-19T13:21:53.073 回答
0

正如 preinheimer 所建议的,标题必须在每个页面输出之前发送。在不使用标题的情况下,您可以使用一行 javascript 代码进行简单的重定向。这可能是您的解决方案:

<?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>
于 2011-06-19T14:10:25.340 回答