Drupal 5: Logging out users after a period of inactivity
Here is the code I used in a module and theme to logout a user after 15 minutes of activity. The code uses jQuery, AJAX, sessions, and a menu callback function to keep track how it’s been since the user loaded a page.
The first piece of code I added was a menu callback to simply output the number of minutes of inactivity, which will be used by AJAX.
Here’s the callback function used:
Next I created a function that will increment the session timestamp. As you can see, I used variable_get(). Whenever I feel like something should be configurable to the site administrator, I make sure to create an admin settings form (which I’m not showing in this example).
I wanted this piece of code to be executed on every page load, so I put it right at the top of my menu hook:
In the head of my theme I added a line of code to set the session timeout so it will be available to jQuery. NOTE: I should have used drupal_add_js(), I’ll have to change my code.
Now if the user leaves their browser open for 15 minutes without clicking on anything, they’ll get a popup window telling them their session expired, they’ll be logged out, and redirected to the homepage. If the user closes their browser and returns to the site a while later, they will also be logged out.