错误提示: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. Use Javascrīpt (用Javascrīpt来解决):

<?php
	echo "<scrīpt> self.location( file.php );</scrīpt>";
?>

可以用Javascrīpt来代替header。另外需要注意,采用这种方法需要浏览器支持Javascrīpt.

3b. Use output buffering (用输出缓存来解决):

<?php ob_start(); ?>
... HTML codes ...
<?php
	... PHP codes ...
	header ("Location: ....");
	ob_end_flush();
?>

就像上面的代码那样,这种方法在生成页面的时候缓存,这样就允许在输出head之后再输出header了。

4.set output_buffering = On in php.ini (开启php.ini中的output_buffering )

这种方法和3b的方法理论上是一样的。但是这种方法开启了所有php程序的输出缓存,这样做可能影响php执行效率,这取决于服务器的性能和代码的复杂度。