Prasad Patel
Prasad Patel

Reputation: 747

how to make user logout after 30 mins of inactivity?

I am using sessions for user login & logout. I have a requirement that after 30 minutes of user inactivity he/she has to logout automatically. I searched & tried few solutions but didn't work though. I tried below solutions:

Solution1:

if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
    echo"<script>alert('15 Minutes over!');</script>";
    unset($_SESSION['email'], $_SESSION['user_id'], $_SESSION['timestamp']);
    session_destroy();
    $_SESSION['logged_in'] = false;
    header("Location: " . index.php); //redirect to index.php
    exit;
} else {
  $_SESSION['timestamp'] = time(); //set new timestamp
}

Solution2:

function auto_logout($field)
{
  $t = time();
  $t0 = $_SESSION[$field];
  $diff = $t - $t0;
  if ($diff > 3000 || !isset($t0))
  {          
    return true;
  }
  else
  {
    $_SESSION[$field] = time();
  }
}
if(auto_logout("email"))
{
  session_unset();
  session_destroy();
  header('Location: index.php');
  exit;
}

Neither of them worked, Could any one please tell me how to track last activity of user and check that time with the current time if exceeds 30 minutes and make that user logout?

Upvotes: 4

Views: 12103

Answers (2)

DevMoutarde
DevMoutarde

Reputation: 597

I think this may help : How do I expire a PHP session after 30 minutes?

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset();     // unset $_SESSION variable for the run-time 
session_destroy();   // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Upvotes: 1

Azeez Kallayi
Azeez Kallayi

Reputation: 2642

If you want to find the activity , you can use the javascript as below and then redirect to logout page to clear the session . here i put 5 sec of inactivity

    var t;
    window.onload = resetTimer();
    // DOM Events
    document.onmousemove = resetTimer();
    document.onkeypress = resetTimer();
    console.log('loaded');

function logout() {
        alert("You are now logged out.")
        //location.href = 'logout.php'
    }

    function resetTimer() {
		
        clearTimeout(t);
        t = setTimeout(logout, 5000)
        
    }

Upvotes: 2

Related Questions