How to register a user due to inactivity

Clean, server-side PHP. Each time a user submits a form, I update the time of the last activity in the database.

I want to do a periodic check and force logout of inactive users in order to free licenses.

How can I do it? Should I also store the session identifier in the database and then destroy the session? This will release the license for another user, and when the first one finally submits another form, which I can check at the top of each form action file if the session still exists and redirects the user to the login page if necessary.

Will this work? Is this the best way? Any code sample?


Update: I am polling because I need to know when the user timeout updates the database.

+4
source share
6 answers

This problem is more complicated than it seems on the surface.

You need to consider session behavior at three different levels:

  • Php
  • Database
  • Browser

Php

For PHP, you need to set the session timeout to what you limit. Here is a sample code from php.net :

<?php session_cache_limiter('private'); /* set the cache expire to 30 minutes */ session_cache_expire(30); session_start(); ?> 

Database

It looks like you need to keep track of how many sessions are active so you can apply your license. Since you are in PHP, you need to do this at the database level. Each request could write a "last request time" for the user ( UPDATE users SET last_access=NOW() WHERE user_id=? ), And then you can assume that the active sessions are the ones that were in the last 30 minutes.

Instead of "last access time", you can try to keep track of active sessions, again in the database. I'm not quite sure how this is best done in PHP. I think you can embed PHP session deletion code. I believe that you can call the function when the session expires, but I did not.

Browser

You can use Javascript polling, but this is not necessary if you have a server side timeout. Consider cases where the user disables Javascript, or you have a Javascript error that causes the script to stop working.

We have a very intensive Ajax site, so Javascript is important. A timeout can be detected when a user does something harmless, like opening a panel on a page. I wrote my recent experience here.

+2
source

Each time you log in, you need to track the start time of the session, which can be done as follows:

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

Each time a user requests to perform any operation, you need to run this script to monitor inactivity.

 <?php session_start(); $TimeOutMinutes = 15; // This is your TimeOut period in minutes $LogOff_URL = "login.php"; // If timed out, it will be redirected to this page $TimeOutSeconds = $TimeOutMinutes * 60; // TimeOut in Seconds if (isset($_SESSION['SessionStartTime'])) { $InactiveTime = time() - $_SESSION['SessionStartTime']; if ($InActiveTime >= $TimeOutSeconds) { session_destroy(); header("Location: $LogOff_URL"); } } $_SESSION['SessionStartTime'] = time(); ?> 
+4
source

You can do this exclusively with JavaScript. Start the countdown timer. Then wait for activity and reset this timer. If there is no activity and the timer goes off, you can call the logout sequence.

for example:

 <body onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()"> <script type="text/javascript"> function set_interval() { //the interval 'timer' is set as soon as the page loads timer=setInterval("auto_logout()",10000); // the figure '10000' above indicates how many milliseconds the timer be set to. //Eg: to set it to 5 mins, calculate 5min= 5x60=300 sec = 300,000 millisec. So set it to 3000000 } function reset_interval() { //resets the timer. The timer is reset on each of the below events: // 1. mousemove 2. mouseclick 3. key press 4. scroliing //first step: clear the existing timer clearInterval(timer); //second step: implement the timer again timer=setInterval("auto_logout()",10000); ..completed the reset of the timer } function auto_logout() { //this function will redirect the user to the logout script window.location="your_logout_script_location_here"; } </script> 

Hope this helps.

PS: Link from: http://www.w3hobbyist.com/web-designing/auto-logout-after-some-time-of-inactivity-with-javascript/

+3
source

I want to do a periodic check and force logout of inactive users to free licenses

I guess what you meant. When the session has (should be) expired, you need to "do something" to free the license, and you want it to be controlled on the server side.

session.gc_maxlifetime hurts here because PHP does not send a notification when it destroys a session.

You need a cron job to scan the PHP session folder for sessions whose time has exceeded your timeout and release their license (and also delete the session). The beginning for such a script is

cd / path / to / sessions; find -cmin +24 | xargs rm

which was taken from the bottom http://www.php.net/manual/en/session.configuration.php#ini.session.gc-maxlifetime You replace xargs rm with something more useful to you.

+3
source

All of these solutions are interesting and work well.

But: What if you are in a frame-based content window?

Then there are two options:

  • Before logging out or causing the script to log out, you need to reach the top of the page based on the frame (it can be done using a JavaScript command that "upsets" the depth of the current position in the frame)

  • Alternatively, a frame driver or other cadre killer script can be called to reset to the upper position, for example

<style> html{display : none ; } </style>
<script>
if( self == top ) {
document.documentElement.style.display = 'block' ;
} else {
top.location = self.location ;
}
</script>

(co WikiPedia: http://en.wikipedia.org/wiki/Framekiller )

More information about frame chests and personnel killers can be read from various sources by a simple Internet search for "framebuster" or "freakiller".

+1
source

Here is my version based directly on RKh's answer.

This version will restart the timer if the session has not expired. Thus, you can insert this entire block directly under your session_start (), and you do not need to call it separately each time the user makes a request to perform an action.

 /* Control Session Timeout */ if (!isset($_SESSION['LastActivity'])) { $_SESSION['LastActivity'] = time(); } //Set Timeout Window in Minutes $TimeOutMinutes = 5; //TimeOut in Seconds $TimeOutSeconds = $TimeOutMinutes * 60; if (isset($_SESSION['LastActivity'])) { $InactiveTime = time() - $_SESSION['LastActivity']; //If Inactive Time more than timeout value log the user out if ($InactiveTime >= $TimeOutSeconds) { session_destroy(); header("Location: $baseURL"); } //If Inactive Time less than timeout reset the last activity to current time elseif ($InactiveTime < $TimeOutSeconds) { $_SESSION['LastActivity'] = time(); } } 
+1
source

All Articles