如果在执行php程序时看到这条警告:"Warning: Cannot modify header information - headers already sent by ...."
有以下几种解决方法:
1. Blank lines (空白行):
检查有<?php ... ?> 后面没有空白行,特别是include或者require的文件。不少问题是这些空白行导致的。
2. Use exit statement (用exit来解决):
在header后加上exit();
header ("Location: xxx");
exit();
3. PHP has this annoying problem, if your HTML goes before any PHP code or any header modification before redirecting to certain page, it'll said "Warning: Cannot modify header information - headers already sent by ...." Basically anytime you output to browser, the header is set and cannot be modified. So two ways to get around the problem:
3a. 用Javascript来解决:
<? echo "<script> self.location(\"file.php\");</script>"; ?>
可以用Javascript来代替header。注意:采用这种方法需要浏览器支持Javascript.
3b. 用输出缓存来解决:
<?php ob_start(); ?>
... HTML codes ...
<?php
... PHP codes ...
header ("Location: ....");
ob_end_flush();
?>
这种方法在生成页面的时候缓存,这样就允许在输出head之后再输出header了。本站的许愿板就是采用这种方法解决的header问题。
4.在php.ini中设定 output_buffering = On
这种方法开启所有php程序的输出缓存,这样做可能影响php执行效率,具体影响程度这取决于服务器性能和代码复杂度。