简体   繁体   中英

How to logout user when $_SESSION variable expires

I'm trying to implement a MySQL table that contains a list of users that are currently logged in. This is my current logic and code to implement this.

On Log In execute the following code:

//Add the user_id to the logged_in table
$loggedInQry = mysqli_query($dbc, "INSERT INTO logged_in (user_id) VALUES ('$userId')");

Upon clicking the Logout button, execute the following code:

//Remove user from logged_in table.
$userId = $_SESSION['userId'];
$logoutQry = mysqli_query($dbc, "DELETE FROM logged_in WHERE user_id = '$userId'");

//Clear all of the saved session variables.
session_destroy();

The problem i'm currently facing however, is that if the session times out after the default 24 minutes, the user is automatically logged out due to the unsetting of the $_SESSION['userId'] variable, however the user_id is not removed from the logged_in table.

Is there a way that a function can be executed on a $_SESSION timeout? Ideally i would like to remove the current $_SESSION['userId'] from the logged_in table upon a Session timeout, as it currently remains in the logged_in table.

You need to implement your own session timeout mechanism so you can execute that same delete query upon timeout.

This will get you going in the right direction: https://solutionfactor.net/blog/2014/02/08/implementing-session-timeout-with-php/

Auto expire session

<?php
session_start();
$idletime=30;//after 60 seconds the user gets logged out
if (time()-$_SESSION['timestamp']>$idletime){
session_destroy();
}else{
$_SESSION['timestamp']=time();
}

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

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