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服务器。然后就出现了报错:
建议还是把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.