tags:

views:

443

answers:

4

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

+1  A: 

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.

pygorex1
Can you give a little bit of explanation on that.
halocursed
A: 

Simply add the cookie expires to 2 days or the number of days you want to remember the user and save the cookie.

Hemanshu Bhojak
+6  A: 

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.

Lukáš Lalinský
+1, don't forget to regenerate the token upon each successful login
stereofrog
Thanks a lot man
halocursed
A: 

PHP' $_SESSION does this for you. You can even write your own session class if you like full control.

A small tutorial is found here: http://www.tizag.com/phpT/phpsessions.php

Here is a small example to use mysql to store sessions instead of php default (files in /tmp): http://www.hawkee.com/snippet/2018/

jonaz