How to update database automatically after session end without refreshing on my page

This code needs to be refreshed or clicked on the page before it goes to the index page and before it refreshes the database after the session expires.

How can I do this automatically, that after the session expires, it will refresh the database so that the user is 0 active without refreshing or clicking on the page?

$idletime = 3600; //after 1hr the user gets logged out

if (time() - $_SESSION['timestamp'] >= $idletime){
    $online = "UPDATE users SET active = 0 WHERE username = '".$_SESSION['username']."'";
    mysqli_query($con, $online);
    session_destroy();
    header("Location:index.php");
} else {
    $_SESSION['timestamp'] = time();
}

      

+3


source to share


2 answers


I suggest using a different approach here. You do not have to update the "active" field in the database. Otherwise, you create a "lastActivity" field in the database and update it every time the user does something on the site.

In this case, you can easily detect which users are inactive by querying the database like this:

SELECT * FROM users WHERE lastActivity < TIMESTAMP(CURRENT_TIMESTAMP() - INTERVAL 1 HOUR);

      



Your PHP code will look like this:

$online = "UPDATE users SET lastActive = NOW() WHERE username = '".$_SESSION['username']."'";
mysqli_query($con, $online);  

      

+2


source


The best option is not to use an active / inactive flag in the database, but rather use something like a last_active

timestamp. When the user accesses the page, update the timestamp to CURRENT_TIMESTAMP()

. And to determine if the user is currently active, a request forWHERE active_timestamp < TIMESTAMPADD(MINUTE, -60, CURRENT_TIMESTAMP())

Make sure to active_timestamp

set active_timestamp

as type in the table structure DATETIME

. ( ALTER TABLE users ADD COLUMN active_timestamp datetime AFTER username'

)



The problem is your script wants to kick the user out when the session is idle. To do this, you have to look at JavaScript, set a timer that counts down for more than 1 hour, and if there is no activity, redirect the page.

+5


source







All Articles