Valentin 给了你正确的答案(支持他/接受他的答案!),但没有解释原因。解释如下:
输出缓冲
PHP 不会立即输出到浏览器,它会等待有一些内容发送到浏览器(可能以 1024、2048 或 4096 字节的块发送),或者在执行结束时。调用flush() 让PHP 发送数据,但是不止一层缓冲。一种是内部缓冲(我刚刚评论过),但您可以添加更多缓冲层。假设这段代码:
<?php
echo "hi";
setcookie('mycookie', 'somevalue');
?>
setcookie() 函数向浏览器发送一个 http 头,但它不能这样做,因为在 HTTP 中,服务器(或客户端,两种方式都相同)必须首先发送所有头,一个空行,然后是内容。如您所见,您在标头之前输出了一些内容(hi),因此它失败了(因为内部缓冲遵循相同的执行顺序)。
您可以使用 php 函数 ob_*() 添加另一层输出缓冲。使用ob 缓冲它只缓冲内容输出,而不缓冲HTTP 标头。您可以使用它们来获取直接输出到浏览器的函数的输出,例如var_dump()。此外,您可以嵌套层ob:
<?php
// start first level of output buffering
ob_start();
echo "nesting at level ", ob_get_level(), "<br />\n"; // prints level 1
echo "hi<br />";
ob_start();
echo "nesting at level ", ob_get_level(), "<br />\n"; // prints level 2
var_dump($_POST);
$post_dump = ob_get_clean();
// this will print level 1, because ob_get_clean has finished one level.
echo "nesting at level ", ob_get_level(), "<br />\n";
echo "The output of var_dump(\$_POST) is $post_dump<br />\n";
// in spite of being inside a layer of output_buffering, this will work
setcookie('mycookie', 'somevalue');
// flush the current buffer and delete it (will be done automatically at the
// end of the script if not called explicitly)
ob_end_flush();
可能您的 PHP 服务器默认启用了 output_buffering。默认情况下,请参阅configuration variables 将其关闭/打开。