Jquery中文网 www.jquerycn.cn
Jquery中文网 >  脚本编程  >  php  >  正文 php Cannot modify header information-headers already sent by解决办法

php Cannot modify header information-headers already sent by解决办法

发布时间:2018-11-29   编辑:www.jquerycn.cn
jquery中文网为您提供php Cannot modify header information-headers already sent by解决办法等资源,欢迎您收藏本站,我们将为您提供最新的php Cannot modify header information-headers already sent by解决办法资源
昨天在使用cookie时页面报错:php Cannot modify header information-headers already sent by了,下面我来总结关于报错的解决办法。

代码

<table width="620" align="center" border="0" cellpadding="1" cellspacing="1" style="background:#FB7"> <tr> <td width="464" height="27" bgcolor="#FFE7CE"> 代码如下</td> <td width="109" align="center" bgcolor="#FFE7CE" style="cursor:pointer;" onclick="doCopy('copy4968')">复制代码</td> </tr> <tr> <td height="auto" colspan="2" valign="top" bgcolor="#FFFFFF" style="padding:10px;" class="copyclass" id=copy4968><?php
ob_start();
setcookie("username","宋岩宾",time() 3600);
echo "the username is:".$HTTP_COOKIE_VARS["username"]."n";
echo "the username is:".$_COOKIE["username"]."n";
print_r($_COOKIE);
?>

Warning: Cannot modify header information - headers already sent by出错的原因

我在php程序的头部加了,

header("cache-control:no-cache,must-revalidate");

原因分析

在PHP里Cookie的使用是有一些限制的。
1、使用setcookie必须在<html>标签之前
2、使用setcookie之前,不可以使用echo输入内容
3、直到网页被加载完后,cookie才会出现
4、setcookie必须放到任何资料输出浏览器前,才送出
.....
由于上面的限制,在使用setcookie()函数时,学会遇到 "Undefined index"、"Cannot modify header information - headers already sent by"…等问题,解决办法是在输出内容之前,产生cookie

解决办法

1在页面顶部的php标签中加入ob_start();

2在返回的信息下面加入ob_end_flush();

这样就可以屏蔽错误信息的现实了


但有的朋友说上面办法不行,后来我后来打开 php.ini 然后把 output_buffering 设为 on 。重起appache,OK。看来这才是解决办法。


另外有朋友说是编码问题,只要转换文档有uft-8就可以解决了,这里就不介绍了。

您可能感兴趣的文章:
php Cannot modify header information - headers already sent by set 解决方法
php Cannot modify header information-headers already sent by解决办法
hp函数setcookie()报错:Warning: Cannot modify header
php Cannot modify header informationheaders already sent by解决方法
解决”Cannot modify header information
php使用session时出现的报错
php报错:Cannot send session cookie – headers already sent by的解决方法
PHP中output buffering的原理及应用
php header & http
php提示”Cannot send session cache limiter

[关闭]