首頁  >  文章  >  後端開發  >  php設定cookie失敗怎麼辦

php設定cookie失敗怎麼辦

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-09-28 15:57:083039瀏覽

php設定cookie失敗怎麼辦

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

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

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

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

相關推薦:《php入門教學

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設定cookie失敗怎麼辦的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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