Cookie not working

Hi guys,

When a user logged in to my site I set up these values to retrieve them later:

[code]$_SESSION[‘name’] = $user[‘name’];

$cookie_time = (3600 * 24 * 15); // 15 days
setcookie (“name”, $_SESSION[‘name’], time() + $cookie_time);[/code]

This is the code that I retrieve the cookie value.

$name = $_SESSION['name'] || $_COOKIE['name'];

I expect when the user close a browser without log out and he revisits the site next day he wouldn’t want to log in again. But it’s not working.

What should be the right code to get this working.
Thank you,

First, some browsers have a setting option to “remove all cookies when closed” so that isn’t 100% reliable.

Second, I have never seen a logical OR used in a variable assignment before. Is that a thing?


If you are probably working with a standard log in form, you should decide which type of remembering system you would like. You can use session(based on browser open/close), and cookie (based on time), you can even use both in a creative way.

But it seems you hit a rock, have you declared session_start() ? additionally remove the “||”, and just use the cookie global var.

I also recommend using only session, as cookies are incredibly insecure due to the client being able to change their content.

Thanks PhPer,

I would explore more about this. You mean user can steal the cookie and hijack a session?

I had written this and tesed(works):

$_SESSION['name'] = "Yourname";
$cookie_time = (3600 * 24 * 15); // 15 days
setcookie ("name", $_SESSION['name'], time() + $cookie_time);

echo $_COOKIE['name'];

To be accurate, anything is hackable , but for a secure login system , saving as less as possible data over the client side, is better. Cookies are stored on client side, while sessions are on the server-side.
You can read more about that just by googling “secure log in” , it will presumably result in neat ways to protect your system.

For example, if there is not Httponly set, then javascript can change the cookie value.