Heim  >  Artikel  >  php教程  >  php Cannot modify header information-headers already sent by解决办法

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

WBOY
WBOYOriginal
2016-05-25 16:52:191294Durchsuche

昨天在使用cookie时页面报错:php Cannot modify header information-headers already sent by了,下面我来总结关于报错的解决办法,代码如下:

<?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必须在标签之前

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就可以解决了,这里就不介绍了。

文章地址:

转载随意^^请带上本文地址!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn