php的setcookie()函數(shù)那槽,在手冊(cè)里有這么一段介紹:
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函數(shù)使用之前,不能有任何輸出信息發(fā)送到客戶端絮供。但是我在用代碼測試的時(shí)候渔彰,發(fā)現(xiàn)php并沒有報(bào)錯(cuò)诚些。代碼如下:
echo "i am going to setcookie";
var_dump(setcookie('buhehe', 'asdasdasdasdad'));
print_r($_COOKIE);
按照php手冊(cè)里的說明,此時(shí)應(yīng)該會(huì)報(bào)錯(cuò)。但是實(shí)際并沒有報(bào)錯(cuò)媚狰。原因是php5.3版本以下時(shí),php.ini有一項(xiàng)配置output_buffering阔拳,這個(gè)output_buffering配置項(xiàng)崭孤,在php5.3以下是默認(rèn)為0。在5.3以上則默認(rèn)是4096糊肠。
因?yàn)槲沂褂玫膒hp5.4辨宠,所以在測試的時(shí)候,默認(rèn)是開啟output_buffering的货裹。
開啟output_buffering的時(shí)候嗤形,無論是echo,還是var_dump弧圆,print_r赋兵,任何輸出,都會(huì)在php腳本結(jié)束時(shí)搔预,統(tǒng)一隨著http響應(yīng)返回給客戶端霹期。(超過4096大小時(shí),可能會(huì)分段返回)拯田。
然后我試著把php.ini里的output_buffering改為0经伙,重啟了nginx服務(wù)器。然后就出現(xiàn)了報(bào)錯(cuò):
建議還是把php.ini里的output_buffering改為4096或者其他合適的數(shù)值勿锅,避免php腳本過早輸出了數(shù)據(jù),導(dǎo)致setcookie報(bào)錯(cuò)枣氧。
關(guān)于output_buffering的介紹溢十,在手冊(cè)里還有這么一段話,可以幫助理解:
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.