Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What should I store in cookies to implement "Remember me" during user login

Tags:

php

cookies

login

I have a login system in place for my website, the details of the user which are stored in the database are userid(unique for every user and identifier), email address(unique), display name(not unique), password and membersince.
Now what should I store in the cookies? I was thinking about storing just the userid in the cookie with an expiration date and then if the user revisits my website after signing up check for the cookie and log him in( which kind of doesn't look right to me) and destroy the cookie if he decides to log out.
*A little explanation would also be very helpful. Thanks

like image 625
halocursed Avatar asked Dec 07 '09 07:12

halocursed


2 Answers

You can only ever store the userid in a cookie if you sign it with a secret key that only your applications knows. Otherwise it's possible for the user to change the cookie to anything and login as somebody else. So, if you want to store the userid, store also a hash of the user id with the secret key (ideally using HMAC) and when you want to log them in, calculate the same hash and compare it to the hash from the cookie. Another solution is to generate a random token, store it in the database and use that in the cookie. If it's long and random enough, there is very little chance somebody would guess another person's token.

like image 60
Lukáš Lalinský Avatar answered Nov 09 '22 00:11

Lukáš Lalinský


PHP has built-in session management that does exactly what you're looking for:

http://us.php.net/manual/en/book.session.php

I wouldn't recommend storing the user_id in the cookie. Instead, you can generate a unique token and associate the token with users in your database, and check & regenerate the token on each request. Again, this is a bit redundant, because session management is already built into PHP.

like image 37
leepowers Avatar answered Nov 09 '22 02:11

leepowers