User’s Inactivity Check and Logout in PHP – Easy One

by Hiroshi on January 18, 2013

in Security

It is an essential professional approach to implement all possible necessary checks while programming webapps. If a user is inactive for certain period of time, you can log him out and clear all session data for security check. This check will build user’s trust in your development skill and he will feel secure while using website that you have developed. So why not alert user if he has been inactive on website for certain period of time? Don’t forget to show message that why he has been logged out. Here is a two lines control for this check.

if(time() > $_SESSION['expire']){
-> clear all sessions and logout
} else {
$_SESSION['expire'] = time()+30*60;

This check will set time to 30 minutes. After 30 minutes user will be automatically logged out, if he has been inactive.

3-Steps Check:

1- User logged in, start session, start session expiry time, like this:

$_SESSION['expire'] = time()+30*60;

We took current time, added 30 minutes in it and stored this in session.

2- At every page check that if 30 minutes (for above script) have been passed or not, like this:

if(time() > $_SESSION[‘expire’]){
-> clear all sessions and logout

if yes, clear session and logout, like this:

if(time() > $_SESSION['expire']){

And then redirect to login page.

3- In else statement (if 30 minutes have not passed), reset time (take current time and add 30 minutes in it and restore in session named ‘expire’) stored in session, like this:

else { $_SESSION['expire'] = time()+30*60; }

…And do nothing – don’t clear sessions, don’t redirect to login page, so that user may stay at website, as much time as he is active.

Ideal way (what I think) is to create a file and include it at every secure page. That file will;

start session
check if admin session values are set
-if not, log him out
check timer session
-if it is more than 30 minutes (or whatever you choose) difference between user’s activity
–log him out
else do nothing and let him use account

Related Posts

Previous post:

Next post: