[thelist] PHP sessions timing out

Simon Willison cs1spw at bath.ac.uk
Mon May 2 09:48:16 CDT 2005


On 2 May 2005, at 14:52, Juha Suni wrote:

> A rather easy and solid solution should be to set your script to  
> store it's sessions elsewhere, where others scripts's garbage  
> collection is not messing around. Another way is to globally  
> increase the gc_maxlifetime from php.ini, but that might not be an  
> option on shared hosting.
>

I've always avoided PHP's built in session stuff for production code  
for pretty much exactly this reason. Instead, I prefer to roll my  
own. I have a sesssions table somewhere that looks a bit like this:

session_id | user_id | date_and_time_they_logged_in

The session_id is a randomly generated string, long enough to be  
"secure". When a user logs in, I create a random session_id, send it  
to them as a cookie and record that along with their user ID and the  
date/time in the database table. Whenever I get a hit to a page from  
someone with a session_id in their cookie, I compare it against the  
table to see if they are logged in (and if they are, load up their  
user details). The date_and_time_they_logged_in thing is handy as  
well as you can enforce things like sessions timing out after 60  
minutes, without trusting the time you set on their cookie (which can  
be altered by the user).

If you want to be really smart, you can add a  
date_and_time_of_last_time_the_user_loaded_a_page_anywhere_on_the_site f 
ield, and then use that to display a list of users active in the last  
10 minutes for "who's online" style functionality.

I'm convinced that sessions based only on the user_id are The Right  
Way To Do It. You end up having to run one database query per page  
loaded to grab the user details which for the vast majority of sites  
is an insignificant performance hit, but you gain the bonus that info  
about the user is "live". A classic problem with storing all sorts of  
information about the user in some session object somewhere is that  
if you ban a user or remove one of their permissions their session  
object won't automatically be updated, so if they're currently logged  
in to the application they'll be able to do things that they shouldn't.

All database table names are for illustrative purposes only ;)

Cheers,

Simon Willison
http://simon.incutio.com/



More information about the thelist mailing list