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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With