Home > php教程 > php手册 > body text

PHP错误Warning: Cannot modify header information

WBOY
Release: 2016-06-13 09:24:52
Original
685 people have browsed it

PHP错误Warning: Cannot modify header information - headers already sent by解决方法,warningheaders

今天在测试以下代码时遇到该错误:

复制代码 代码如下:


session_start();
$_SESSION['username']=$username;
echo "";
exit();

出现错误:

复制代码 代码如下:


Warning: Cannot modify header information - headers already sent by...

看了一些网上的方法也没解决,最后在php.ini配置output_buffering默认为4096就没有遇到这个错误了:

output_buffering设置说明:

    Off: 表示关闭PHP输出缓存
    On: 打开无限大的输出缓存
    4096: 打开大小为4096Byte的输出缓存

默认情况下,php buffer是开启的,而且该buffer默认值是4096,即4kb。你可以通过在php.ini配置文件中找到output_buffering配置.当echo,print等输出用户数据的时候,输出数据都会写入到php output_buffering中,直到output_buffering写满,会将这些数据通过tcp传送给浏览器显示。你也可以通过ob_start()手动激活php output_buffering机制,使得即便输出超过了4kb数据,也不真的把数据交给tcp传给浏览器,因为ob_start()将php buffer空间设置到了足够大。只有直到脚本结束,或者调用ob_end_flush函数,才会把数据发送给客户端浏览器。

关于output_buffering详细介绍可以参考:

http://www.bkjia.com/article/55707.htm

补充:当然你也可以通过去除BOM解决这个问题,建议以UTF-8无BOM格式编码。感谢 @ihipop 童鞋
关于BOM,简单的来说,软件通过BOM来识别这个文件是否是UTF-8编码。在Firefox早期的版本里,扩展是不能有BOM的,不过Firefox 1.5以后的版本已经开始支持BOM了。现在又发现,PHP也不支持BOM。PHP在设计时就没有考虑BOM的问题,也就是说他不会忽略UTF-8编码的文件开头BOM的那三个字符。

其中有提到另一个麻烦:“受COOKIE送出机制的限制,在这些文件开头已经有BOM的文件中,COOKIE无法送出(因为在COOKIE送出前PHP已经送出了文件头),所以登入和登出功能失效。一切依赖COOKIE、SESSION实现的功能全部无效。”这个应该就是Wordpress后台出现空白页面的原因了,因为任何一个被执行的文件包含了BOM,这三个字符都将被送出,导致依赖cookies和session的功能失效,所以你也可能遇到如下错误:

复制代码 代码如下:


Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started at E:\web\index.php:1) in E:\web\functions\sessions.php on line 39

PHP页面错误:Warning: Cannot modify header information - headers already sent by

打开 php.ini 然后把 output_buffering 设为 on 。重起appache,OK。
 

PHP测试出错,Warning: Cannot modify header information - headers already sent by

1、 sessionstart一般不用调用,有服务器自动处理。
2、两段script代码应该放到

或中的适当位置。
3、你的“header("location:login.php");”代码应该放到“#47;/W3C。。。。”的前面。输出了“#47;/W3C”就不允许你修改header了。
 
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!