Force Logout users if users are inactive for a certain period of time
If the user is requesting new pages/data from your server on a regular basis, then adjusting the session timeout in PHP should work for this (assuming you are using PHP sessions).
If the concern is that they could be sitting on one page for a good length of time with no trips to the server (e.g. filling out a long form), and you want to distinguish between this and the user simply switching to another window, you could do something like use javascript to request some data using XMLHTTPRequest every five minutes or so to keep the session alive. You could use the window.focus and window.onblur events in javascript to stop and restart this mechanism (I think there are some differences for IE, there is a good explanation here).
How to log users off automatically after a period of inactivity?
You have to implement it with a kernel listener, this is the way I solve it:
Listener src/Comakai/MyBundle/Handler/SessionIdleHandler.php
namespace Comakai\MyBundle\Handler;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class SessionIdleHandler
{
protected $session;
protected $securityToken;
protected $router;
protected $maxIdleTime;
public function __construct(SessionInterface $session, TokenStorageInterface $securityToken, RouterInterface $router, $maxIdleTime = 0)
{
$this->session = $session;
$this->securityToken = $securityToken;
$this->router = $router;
$this->maxIdleTime = $maxIdleTime;
}
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST != $event->getRequestType()) {
return;
}
if ($this->maxIdleTime > 0) {
$this->session->start();
$lapse = time() - $this->session->getMetadataBag()->getLastUsed();
if ($lapse > $this->maxIdleTime) {
$this->securityToken->setToken(null);
$this->session->getFlashBag()->set('info', 'You have been logged out due to inactivity.');
// Change the route if you are not using FOSUserBundle.
$event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
}
}
}
}
Config src/Comakai/MyBundle/Resources/config/services.yml (Comakai/MyBundle/DependencyInjection/MyBundleExtension.php)services:
my.handler.session_idle:
class: Comakai\MyBundle\Handler\SessionIdleHandler
arguments: ["@session", "@security.context", "@router", %session_max_idle_time%]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
Now you can set the session_max_idle_time
in parameters.yml to 30 * 60 = 1800 seconds (or just hardcode the value wherever you want):Parameters app/config/parameters.yml
parameters:
...
session_max_idle_time: 1800
how to auto log out if user is inactive for some specific duration using codeigniter
// Add the following into your HEAD section
var timer = 0;
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 300000
}
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
if (timer != 0) {
clearInterval(timer);
timer = 0;
// 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.php";
}
// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"
How to handle inactive users and log them out in react JavaScript?
This can be achieved by JavaScript only.
Since our web app can be open in multiple tab, so its better to store last activity of user in localStorage
First lets declare events which we consider as user activity and store time of user activity in localStorage
document.addEventListener("mousemove", () =>{
localStorage.setItem('lastActvity', new Date())
});
document.addEventListener("click", () =>{
localStorage.setItem('lastActvity', new Date())
});
Next lets create interval which will be checked on every given interval.let timeInterval = setInterval(() => {
let lastAcivity = localStorage.getItem('lastActvity')
var diffMs = Math.abs(new Date(lastAcivity) - new Date()); // milliseconds between now & last activity
var seconds = Math.floor((diffMs/1000));
var minute = Math.floor((seconds/60));
console.log(seconds +' sec and '+minute+' min since last activity')
if(minute == 10){
console.log('No activity from last 10 minutes... Logging Out')
clearInterval(timeInterval)
//code for logout or anything...
}
},1000)
Automatically log out the user if he is not active for a certain period of time
Looks like you only have the index.php. Try to modify your code like this:
<?
if ((time() - $_SESSION['last_activity']) > 1800) // 30* 60 = 1800
{
header("Location: logout.php");
} else {
$_SESSION['last_activity'] = time();
}
?>
This will only update your session, if the user did something under your 30 mins.Seems like you don't use a library, so you could need to implement this on every site you have.
EDIT
Create a new file, which could be named as lifesaver.php
or something like this. In this file, you paste the code from above.
Now you include it on every page you have, like this: require('lifesaver.php');
This will include your file and you have the code from above in your site.
Explanation how the code from above works:
EDIT: Basically reload the page in 30 or greater minutes and you'll automatically be taken to
logout.php
. If you reload the page sooner than 30 minutes your time will be updated(meaning another 30 minutes till automatic logout). The code is executed every time a user reloads or goes to a page with this script. – Antono
How to logout an inactive user in django?
You have the right setting for logging out part but your system is not informing the active requests to the session table, therefore system explicitly needs to save your new requests to session table which will updates timeout to expire.
In your Settings.py
SESSION_EXPIRE_AT_BROWSER_CLOSE = True # opional, as this will log you out when browser is closed
SESSION_COOKIE_AGE = 300 # 0r 5 * 60, same thing
SESSION_SAVE_EVERY_REQUEST = True # Will prrevent from logging you out after 300 seconds
How to log user out due to inactivity
This problem is more difficult than it seems on the surface.
You need to consider the session behavior at three different levels:
- PHP
- database
- browser
For PHP, you'll need to set the session timeout to whatever you limit is. Here's some example code from php.net:
<?php
session_cache_limiter('private');
/* set the cache expire to 30 minutes */
session_cache_expire(30);
session_start();
?>
DatabaseSounds like you need to keep track of how many sessions are active so you can enforce your license. Since you're in PHP, you'll 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 surmise that active sessions are the ones within the last 30 minutes.
Rather than "last access time", you can try to keep track of the active sessions, again in the database. I'm not exactly sure how this is best done in PHP. I think you can patch into the PHP's session deletion code. I believe it's possible to have it call a function when a session expires, but I haven't done this.
Browser
Javascript polling can be used, but is not necessary, as long as you have a server side timeout. Consider cases where the user turns off Javascript, or you have some Javascript error that causes script to stop running.
We have a very Ajax intensive site, so Javascript is important. A timeout might be discovered when the user does something as innocuous as open a panel on a page. I wrote up my recent experience here.
Related Topics
PHP Upload File Enhance Security
MySQL Fulltext Search Multiple Words
Get the Get Variables from a Url String
Best Way to Get Hostname with PHP
PHP Class: Global Variable as Property in Class
Mongodb: Benefit of Using Objectid VS a String Containing an Id
Check If SQL Row Exists with PHP
Can One Modify the Templates Created by Artisan Migrate Command
How to Use Laravel Passport with a Custom Username Column
File_Get_Contents('Php://Input') Always Returns an Empty String
How to Increase by 1 All Keys in an Array
Codeigniter Force Download Files
PHP - Display a 404 Error Without Redirecting to Another Page
How to Reference a Column Other Than 'Id' for a Joincolumn
.Htaccess Deny Access to Specific Files? More Than One
MySQL Insert ....On Duplicate Update - Adds One to the Autoincrement