views:

221

answers:

4

What is the best thing to store in a cookie to keep a persistent logged-in state?

I have seen many websites (and beginner tutorials!) that simply store something like validUser=1 in a cookie. Clearly I could spoof that and the website would think I was a valid user.

If the username is stored in the cookie I could masquerade as any user by sending a cookie with his/her username in my request.

So if you store the username and password in the cookie, then I must know the username and password to log in. Effectively the user is logged in automatically – it is like having the password saved by his browser. Instead of having to type the credentials into the boxes himself every time, the browser automatically sends them with every page request.

But is this still a bad idea? Storing a plain text password is not a brilliant idea, but that's how it would be sent in the POST data when logging in. And besides, it could be stored hashed. But I still don't feel comfortable with it.

Perhaps cookies should not be used to store anything except a session ID, and the user data is stored on the server itself. That is perhaps a more secure location for it, presuming that the server is not shared.

Looking at some open source software such as forum software, they use a more complicated system, but I couldn't understand exactly what it was doing from skimming the code.

What is the standard "best practice"?

+3  A: 

Best practice would be to use a SESSION instead of a COOKIE for use data. COOKIES are used to store generic information not specific information about a user, that's what SESSIONS are used for.

Phill Pafford
A: 

The best practice is to store a randomly generated session id. The session then stores the user id or whatever else you need it to store. In PHP the session_start() method automatically generates the session id and a cookie named PHPSESSID, so you only need to worry about storing data in the $_SESSION array, not in the cookie.

Luca Matteis
A: 

The only thing that should be in a cookie is the sessionid generated by PHP (and this is done automatically when you use sessions). You should not store anything in the cookie except maybe a remembered username for the purpose of a "remember me" checkbox.

ryeguy