简体   繁体   中英

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?

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) } 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM