PHP:Cannot modify header information

<?php 
ob_start();
setcookie("username","test",time()+3600);
echo "the username is:".$HTTP_COOKIE_VARS["username"]." ";
echo "the username is:".$_COOKIE["username"]." ";
print_r($_COOKIE);
?

>
訪问该PHP文件时提示Warning: Cannot modify header information - headers already sent by。出错的原因
原因是在php程序的头部加了,header("content-type: text/html; charset=utf-8");之后页面就出现上面的错误。

由于 header('Content-Type:text/html;charset= UTF-8');发送头之前不能有不论什么输出,空格也不行,你须要将header(...)之前的空格去掉,或者其它输出的东西去掉,假设他上面include其它文件了,你还要检查其它文件中是否有输出。


上网查了一些资料。说是我的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();//输出所有内容到浏览器 
?>

版权声明:本文博客原创文章,博客,未经同意,不得转载。

原文地址:https://www.cnblogs.com/mengfanrong/p/4615826.html