星外飞客

<?php
header("cache-control:no-cache,must-revalidate");
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.ini 把 output_buffering = Off 改为 output_buffering = On 问题即解决。buffering 默认大小为 4096.

原因是setcookie函数必须在在向浏览器输出内容之前首先输出,基于上面这些限制,所以常常会碰到"Undefined index"、"Cannot modify header information – headers already sent by"…等问题,解决"Cannot modify header information – headers already sent by"这种问题的方法就是在产生cookie之前,延缓内容输出到浏览器,因此,您可以在程序的最前方加上ob_star()函数(要求先开启  output_buffering)。

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;
}

版权所有,转载请注明出处。
转载自 <a href="http://www.yanghengfei.com/archives/329/" title="php output_buffering" rel="bookmark">php output_buffering | 星外飞客 </a>

我简单说几句

随机推荐

最新评论

无觅相关文章插件,快速提升流量