php setcookie 出错,PHP setcookie()之前不能有任何输出

php的setcookie()函数,在手册里有这么一段介绍:setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including  and  tags as well as any whitespace.

大致意思是:setcookie函数使用之前,不能有任何输出信息发送到客户端。但是我在用代码测试的时候,发现php并没有报错。代码如下:echo "i am going to setcookie";

var_dump(setcookie('buhehe', 'asdasdasdasdad'));

print_r($_COOKIE);

按照php手册里的说明,此时应该会报错。但是实际并没有报错。原因是php5.3版本以下时,php.ini有一项配置output_buffering,这个output_buffering配置项,在php5.3以下是默认为0。在5.3以上则默认是4096。

因为我使用的php5.4,所以在测试的时候,默认是开启output_buffering的。

开启output_buffering的时候,无论是echo,还是var_dump,print_r,任何输出,都会在php脚本结束时,统一随着http响应返回给客户端。(超过4096大小时,可能会分段返回)。

然后我试着把php.ini里的output_buffering改为0,重启了nginx服务器。然后就出现了报错:

1e89de198f9f

建议还是把php.ini里的output_buffering改为4096或者其他合适的数值,避免php脚本过早输出了数据,导致setcookie报错。

关于output_buffering的介绍,在手册里还有这么一段话,可以帮助理解:

You can use output buffering to send output prior to the call of this function, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling ob_start() and ob_end_flush() in your script, or setting the output_buffering configuration directive on in your php.ini or server configuration files.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值