Jump to content
Larry Ullman's Book Forums

Simple Code To Automatically Log Out User After Inactivity?


Recommended Posts

I was hoping that someone might be able to provide a few lines of code that would automatically log the user out after 20 or 30 minutes of inactivity.

 

Maybe the code could be placed in the config.inc.php file so that it gets run frequently?

 

(Note: I am using the "First Site" as created in chapters 1-6 of Larry's book.)

 

Thanks!

Link to comment
Share on other sites

Every time a new page is loaded, store the time in a session variable, and then check that it has not exceeded a certain limit since the last time a user has viewed a page. For example:

 

function checkTimeout($timeout = 600) {
  if ($timeout !== 0 && isset($_SESSION['last_time']) && time() - $_SESSION['last_time'] > $timeout)  {
    // Log user out.
  }
  
  $_SESSION['last_time'] = time();
}
 
Note that the above defaults the timeout time to 10 minutes, but it can be set to whatever you want, and by passing an argument of 0, no timeout will ever occur.
Link to comment
Share on other sites

Thanks @HartleySan (fellow Buckeye!); that makes sense.

 

 

Newbie followup question: This method assumes that the user will perform some activity (like loading a page) that will then log them out using your function; is there a way to log them out automatically without them performing an action?  So if they simply close their browser without ever logging out?  

 

I assume this would have to take place on the server side, and perhaps would be too complicated, but thought I'd ask for security reasons.

Link to comment
Share on other sites

Go Bucks!

 

You can do any number of things, but I think there may be a bit of a misunderstanding on your part.

If the user just closes their browser, the next time they go back to the page, the session will still be active and contain the last action time of the user, thus everything would still work fine.

As such, I don't think you need to do anything special to handle the case you suggested (unless I'm missing something or misunderstanding your question).

 

As for logging them out without the user taking an action, yes, you absolutely can do that, but you will have to use JavaScript, as Larry suggested.

Personally, I don't feel that doing all that is necessary though because as far as I'm concerned, if a user just sits on the same page all day, it doesn't bother me because they're not seeing any new content, so I don't feel the need to automatically log them out of the system.

 

You can go either way on that though, and it really depends on the sensitivity of what you're displaying.

If you require a JS solution though, let us know. Otherwise, I think you're fine.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...