Page 1 of 1

[solved] Best Practice to: Keep a user logged in

Posted: Tue Aug 22, 2006 12:52 pm
by paladaxar
I'm sort of new to the world of PHP, so forgive my ignorance.

The server that I am using kills all idle sessions after a short time (20 minutes I think). But, it's the type of site that some people need to keep open all day and use speratically throughout the day. so...

I am wondering: what is the best practice for keeping a user logged into a site?

Since I'm on a shared server, I'm assuming that the only way to keep someone logged in (who may walk away from their computer for a few hours), is to use cookies. I have heard that it is bad practice to keep passwords stored in cookies. But, I cant save the username alone, because anyone could save a username into a cookie variable and get logged in as that user.

So, one thing that I thought of was to make a sort of "temporary password". I would add a columb to my user table named "temp_pw" and make the value something random like a timestamp. Then, save the user name and temporary password into a cookie when the user first logs in. Then, when my script that checks if a user is logged in or not comes accross the two cookies, it would check the db to see if the username/temp pw are a valid match. If there is a match, it would basically go through the proccess of logging in the user (loading up the session with the appropriate variables) and continue as if the user had never logged off.

I hope all that made sense. It sounds to me like it should work, but I'm not sure if it's the best practice. Or even if it is a practice at all...I just kind of made it up.

Posted: Tue Aug 22, 2006 1:05 pm
by pickle
I fix this by using a session ID. When someone logs in, a unique ID is generated for their 'session' & stored in the database along with their username. That information is also stored in their cookie. It's darn near impossible for someone to create a cookie that properly matches up a valid username with a completely random, 64 character string. That way, their password isn't stored anywhere either.

Posted: Tue Aug 22, 2006 1:10 pm
by paladaxar
so you basically do exactly what I was describing above, but you use the session id where i suggested using a timestamp?

And is that what is normally done? This will be the fisrt time that I have implemented this type of function.

Posted: Tue Aug 22, 2006 1:55 pm
by pickle
To the best of my knowledge ya - that's what's normally done.

It's better to use a random session ID than a timestamp though. If I know a username, it's much easier for me to set my cookie & cycle through timestamps, than it is to cycle through every possible permutation of a 64 character (or 32, or 128, or whatever) session id.

Posted: Tue Aug 22, 2006 1:57 pm
by paladaxar
Awesome. Thanks.