简体   繁体   中英

PHP Cookie doesn't work

I'm trying to access a cookie I just set in an other page on the same domain, but it doesn't work. When I'm doing echo $_COOKIE , the array is empty on the new page, but contains the cookie on the creation page.

Here is the code in /PROC/LOGIN.PROC.PHP

//Set the cookie for 1 year.
setcookie("username", $username, time()+365*24*60*60);
setcookie("password", $password, time()+365*24*60*60); 

Here's the code in /INC/HEADER.INC.PHP

if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
include("pages/user.header.pages.php");

But when I'm trying to isset the cookie or only display the array in header.inc.php, the array is empty.

You need to set the path value of the cookie to the root of your domain, as per the docs :

setcookie("username", $username, time()+365*24*60*60, '/');

Otherwise, it will be set to the current working directory, which is /PROC/ for your example. So, only scripts in /PROC/ would be able to use that cookie.

Check out, your PHP setcookie definition is done before declare HEADs. If not, the cookie is not stored.

So take control of your cookies at the beginning of code, before sending headers or other HTML entities.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM