Skip to content
Advertisement

PHP autologout inactive users

first time poster here, finally decided to make an account here after i used too many hours of my workday trying to solve this problem yesterday.

so i have this “sessionCheck.php” script that is supposed to logout the user if he is inactive see code below. Right now the variable $inactive = 15; which should mean that if the user is inactive for 15 seconds, they should be logged out and redirected to the logout page. However for some weird reason, this always takes 120seconds, no matter if i set $inactive to 15 seconds, 1 second or 60 seconds, it always takes 120 seconds. but if i set the variable to lets say 130, it doesn’t logout and redirect at all anymore, only refreshes the page.

I can’t for the life of me figure out why, as it doesn’t really seem logical.

<?
session_start();

// set timeout period in seconds
$inactive = 15;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
        { session_destroy(); header("Location: login.php?loggut");
        $db->Execute("UPDATE tblTimeLog SET LogoutTime = NOW() WHERE sid ='".session_id()."'".$row['konsulentid'].'');

        }
}
$_SESSION['timeout'] = time(); ?>

My first thought was that it must be some other script that overrides or automatically logs the user out already someone interfering with this script, but if i run the test site without this script it doesn’t logout at all either.

Again, first time poster, so sorry if break any guidelines, i’m fairly certain that i didn’t tho! all help is appreciated!

Advertisement

Answer

I would advice to put the header redirect after the query and exit the script so you can be sure the query is processed and the $_SESSION['timeout'] is not updated after you try to logout the user.

You are also destroying the session before you use the actual session_id() in your query once more.

Give this a try:

<?
session_start();

// set timeout period in seconds
$inactive = 15;
// check to see if $_SESSION['timeout'] is set
if(isset($_SESSION['timeout']) ) {
    $session_life = time() - $_SESSION['timeout'];
    if($session_life > $inactive)
        { 
               $db->Execute("UPDATE tblTimeLog SET LogoutTime = NOW() WHERE sid ='".session_id()."'".$row['konsulentid'].'');
               session_destroy(); 
               header("Location: login.php?loggut");
               exit(); 
        }
}
$_SESSION['timeout'] = time(); 
?>
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement