views:

55

answers:

5

I want my users to be logged out automatically after X minutes of inactivity. I also want to have all sessions destroyed.

How can this be done? How can I check for inactivity then perform a function to log them out???

A: 

Depending on how fast your server is and how many users you have, you can have it send a request to your server whenever a user does anything (navigates, clicks a button, whatever). From this request, update a SQL table with their last activity time.

Have a cron job run through the table at some regular interval and delete the sessions of the users that have been inactive for whatever your threshold is going to be.

If your server is slow or you have a lot of users, you can have this script run infrequently.

Jamie Wong
+1  A: 

You can set session time out limit like:

ini_set('session.gc_maxlifetime',30);

Here is the possible solution for you.

Sarfraz
A: 

Use unset($_SESSION['NAME']); or session_destroy();. You could also change the value of the session.

To do this at a certain time, you would need to set a timestamp in the database, and then call it to check if it's beyond X minutes. Look at the link at the bottom.

I'd personally just use cookies and make them expire at a certain time, but whatever floats your boat.

http://stackoverflow.com/questions/3053227/if-current-time-is-more-than-30-seconds-past-time-x-from-the-database

Sam
A: 

You could also do:

$_SESSION['loginTime'] = time();

On every page, and when the user is trying to navigate and he has been inactive for an twenty minutes you can log him out like this:

if($_SESSION['loginTime'] < time()+20*60){ logout(); }
Machiel
A: 

PHP's session mechanism already have a garbage collector based on the inactivity timeout. You have no worry about.

Col. Shrapnel
A bit misleading - garbage collection has nothing to do with when a session becomes disabled - only the time (later) that data is cleared up. The answer is the session lifetime (which confusingly is prefixed by gc_)
symcbean