outbuffer 输出缓冲的理解

来源:互联网 发布:鲁东大学网络教育报名 编辑:程序博客网 时间:2024/05/01 00:19

       在header和setcookie之前有任何的输出就会有警告错误,Warning: Cannot modify header information - headers already sent by

所以当脚本有任何输出的时候, php会先发送header信息给客服端, 然后发送输出内容,(即http协议中的主体内容),这是如果你就不可能对已经发送的header信息进行任何的修改了,所以我们就不可能利用header 和setcookie等修改header的函数做任何事情了!

           解决办法: php的outbuffer 输出缓冲,php的输出缓冲是这样的 ,将当前脚本的所有输出内容都放到outbuffer里面,当程序执行完毕之后 将header和outbuffer一并发送给客户端。

<?php

ob_start();

echo "test";

header("content-type:text/html;charset=utf-8");

setcookie();

?>

这样的话 在header和setcookie前 echo输出将不回出现 warning:cannot modify;

<?php
ob_start();
echo "you are beautyful";

header("content-type:text/html;charset=utf-8");
$length = strlen(ob_get_contents());
ob_end_clean();
echo $length;
?>

将输出17, 语句的字节数, 而you are beautyful 没有输出

 

关于outbuffer还有一些函数:

ob_flush()
发送output buffer(输出缓冲)

ob_end_flush()
发送output buffer(输出缓冲)并禁用output buffering机制。

ob_end_clean()
清除output buffer但不发送,并禁用output buffering。

ob_get_contents()
将当前的output buffer返回成一个字符串。允许你处理脚本发出的任何输出。

ob_get_clean()
将当前的output buffer返回成一个字符串。允许你处理脚本发出的任何输出,并禁用output buffering机制。

     

原创粉丝点击