Jay Viluan
Jay Viluan

Reputation: 1691

How to update the database automatically after session is expired without refreshing on my page

This code you need to refresh or click the page before it will go to index page and before it will update the database after the session is expired.

How can I make it automatically that after session is expired it will update the database so the user active will be 0 without refreshing or clicking on 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();
}

Upvotes: 3

Views: 2998

Answers (2)

Kevin Nagurski
Kevin Nagurski

Reputation: 1889

Best option is to not use an active/not active flag in the database, but rather use something like a last_active timestamp. When the user accesses a page, update the timestamp to CURRENT_TIMESTAMP(). And to determine whether the user is currently active, query for WHERE active_timestamp < TIMESTAMPADD(MINUTE, -60, CURRENT_TIMESTAMP())

Make sure you set active_timestamp as a DATETIME type in the table structure. (ALTER TABLE users ADD COLUMN active_timestamp datetime AFTER username')

The problem here is that your script looks to want to kick the user out when the session is idle. For this, you should look at JavaScript, set a timer that counts down over 1 hour and if there is no activity, redirect the page.

Upvotes: 5

Stepashka
Stepashka

Reputation: 2698

I'd suggest to use a different approach here. You should not update the 'active' field in the database. Otherwise you create 'lastActivity' field in the DB and update it every time user do 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:

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

Upvotes: 3

Related Questions