Home  >  Article  >  php教程  >  Cannot modify header information出错的原因

Cannot modify header information出错的原因

WBOY
WBOYOriginal
2016-06-13 11:39:341026browse

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");
之后页面就出现上面的错误,看了N个资料也没有结果。今天偶尔发现原来是我的php.ini里面的配置出了问题,在C:\windows\下找到php.ini文件
output_buffering默认为off的。我现在把它设为4096就OK了。
用于解决显示提示错误,不能按(日期+导出文件数)为文件名的错误信息.
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()输出都会进入缓冲区而不会立刻输出.当然打开缓冲区的作用很多,只要发挥你的想象.可以总结以下四点:

1.用于header()之前

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

2.phpinfo()函数可获取客户端和服务器端的信息,但要保存客户端信息用缓冲区的方法是最好的选择.
ob_start(); //打开缓冲区
phpinfo(); //使用phpinfo函数
$info=ob_get_contents(); //得到缓冲区的内容并且赋值给$info
$file=fopen(\'info.txt\',\'w\'); //打开文件info.txt
fwrite($file,$info); //写入信息到info.txt
fclose($file); //关闭文件info.txt
?>

3.静态页面技术
ob_start();//打开缓冲区
?>
php页面的全部输出
$content = ob_get_contents();//取得php页面输出的全部内容
$fp = fopen("output00001.html", "w"); //创建一个文件,并打开,准备写入
fwrite($fp, $content); //把php页面的内容全部写入output00001.html,然后……
fclose($fp);
?>

4.输出代码
Function run_code($code) {
If($code) {
ob_start();
eval($code);
$contents = ob_get_contents();
ob_end_clean();
}else {
echo "错误!没有输出";
exit();
}
return $contents;
}

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