Home  >  Article  >  Backend Development  >  PHP:Cannot modify header information

PHP:Cannot modify header information

WBOY
WBOYOriginal
2016-06-23 13:49:22928browse

ob_start();
setcookie("username","test",time()+3600);
echo "the username is:".$HTTP_COOKIE_VARS["username"]."\n";
echo "the username is:".$_COOKIE["username"]."\n";
print_r($_COOKIE);
?>
访问该PHP文件时提示Warning: Cannot modify header information - headers already sent by出错的原因
原因是在php程序的头部加了,header("content-type: text/html; charset=utf-8");之后页面就出现上面的错误。上网查了一些资料,说是我的php.ini里面的配置出了问题,找到php.ini文件中的output_buffering默认为off的,把它改为on或者任意一个数字,但尝试无结果。

setcookie函数必?在任何资料输出至浏览器前,就先送出
基于上面?些限制,所以?行setcookie()函数时,常会碰到"Undefined index"、"Cannot modify header information - headers already sent by"…等问题,解?"Cannot modify header information - headers already sent by"????的方法是在产生cookie前,先延缓资料输出至浏览器,因此,您可以在程式的最前方加上ob_start()函?。


ob_start()函数用于打开缓冲区,比如header()函数之前如果就有输出,包括回车\空格\换行\都会有"Header had all ready send by"的错误,这时可以先用ob_start()打开缓冲区PHP代码的数据块和echo()输出都会进入缓冲区而不会立刻输出:

通过以下方法,问题得到解决:

//在header()之前

ob_start(); //打开缓冲区 
echo \"Hellon\"; //输出 
header("location:index.php"); //把浏览器重定向到index.php 
ob_end_flush();//输出全部内容到浏览器 
?>

Statement:
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
Previous article:关于 herfNext article:mysql获取关联表下最新数据