Reputation: 91
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.
Upvotes: 4
Views: 8891
Reputation: 891
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.
Upvotes: 2
Reputation: 59699
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.
Upvotes: 13