首頁  >  文章  >  後端開發  >  php setcookie 報錯怎麼辦

php setcookie 報錯怎麼辦

藏色散人
藏色散人原創
2021-07-09 09:57:032130瀏覽

php setcookie報錯是因為setcookie()之前有輸出,其解決方法就是將輸出的echo的資料和header頭的cookie一起發出去即可。

php setcookie 報錯怎麼辦

本文操作環境:windows7系統、PHP7.1版,DELL G3電腦

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 <html> and <head> tags as well as any whitespace.

大致意思是setcookie之前不能有東西輸出到客戶端瀏覽器,否則會報錯。但是經測試發現,並沒有報錯。繼續翻看手冊:

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.

於是我修改了php.ini(PHP版本5.4)的output_buffering為0,也就是關閉緩衝區。 (PHP5.3版本以下是關閉的,5.3之後是預設開啟,值為4096)

意思是如果在輸出cookie之前,設定了ob_start和ob_end_flush來輸出緩衝區,則不會報錯。那麼,為什麼cookie和緩衝區的資料一起回傳就沒有報錯呢?應該是因為:緩衝區的資料將整理成一個完整的HTTP包發出去。

我們可以看一下報錯訊息:

echo "i am going to setcookie";
 
var_dump(setcookie(&#39;buhehe&#39;, &#39;asdasdasdasdad&#39;));
 
print_r($_COOKIE);

php setcookie 報錯怎麼辦

#「請不要修改header訊息,因為header已經發送過了。」很明顯,沒有使用緩衝區輸出,則header先一步回到瀏覽器了,然後再進行setcookie發送header頭資訊的時候,就報錯啦-不符合HTTP協定的規範。因為HTTP協定規定header應該在body之前輸出。

我把程式碼修改了一下,把將輸出的echo的資料和header頭的cookie一起發出去。

ob_start();
echo "i am going to setcookie";
 
var_dump(setcookie(&#39;buhehe&#39;, &#39;asdasdasdasdad&#39;));
 
ob_end_flush();
 
print_r($_COOKIE);

結果如下:

php setcookie 報錯怎麼辦

當你設定output_buffering為0也就是在php.ini關閉緩衝區的時候,就需要手動ob_start來開啟緩衝區了。

為什麼有些開發者測試的時候,發現setcookie之前echo了資訊也沒有報錯呢?

因為目前大部分的PHP應用都是5.3 的,有些甚至用上了7。 PHP5.3 版本中,因為預設開啟了緩衝區,並且預設size為4096,所以在setcookie之前echo的數據,以及cookie的header頭信息,都會在緩衝區被封裝成HTTP包,發給客戶端啦~所以也就不會產生上圖中的報錯資訊(請勿修改HTTP的header頭資訊)啦~~

#推薦學習:《PHP影片教學

以上是php setcookie 報錯怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn