Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Cookie doesn't work

Tags:

php

cookies

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.

like image 287
Jean-François Poulin Avatar asked Dec 11 '22 22:12

Jean-François Poulin


2 Answers

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.

like image 86
nickb Avatar answered Dec 28 '22 01:12

nickb


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.

like image 20
Rafa Avatar answered Dec 28 '22 03:12

Rafa