首頁  >  文章  >  後端開發  >  php cookie失效怎麼辦

php cookie失效怎麼辦

藏色散人
藏色散人原創
2020-07-08 10:31:573026瀏覽

php cookie失效是因為當setcookie中第4個參數為空的話,預設只在目前目錄生效,其解決方法就是新增第4個參數,語句為「setcookie("id",$id , time() 36002430 ,'/');」。

php cookie失效怎麼辦

PHP設定cookie無效問題原因以及解決方案

#在某個頁面中使用setcookie來設定cookie,例如

setcookie("id",$id, time()+36002430);

但回到首頁之後發現沒有生效,用javascript:alert(document.cookie)裡面為空,PHP裡面的$_COOKIE也是沒有資料。

跑到PHP官網查看setcookie的說明,官網的例子也是這樣的,但是仔細看來參數說明之後就發現問題了。

setcookie的第4個參數是path

The path on the server in which the cookie will be available on. If set to ‘/’, the cookie will be available within the entire domain. If set to ‘/foo/’, the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain. The default value is the current directory that the cookie is being set in.

也就是說如果第4個參數為空的話,預設只在目前目錄生效,一般情況下是沒有問題的。

但是我的網站設定了rewrite,把index.php給隱去了,所以設定的cookie變成只在該頁面有效。

解決方案就是新增第4個參數

setcookie("id",$id, time()+36002430 ,'/');

更多相關知識,請造訪PHP中文網

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

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