Is there a realistic way of knowing when the session of logged in user died ? I mean, When the user close the browser tab and his logged in session died
-
Yeah you can set a query in logout page to get logout time with user id and store them somewhere. – Apr 19 '22 at 23:54
-
@Dlk did not read the question. – Michael Mano Apr 20 '22 at 00:01
-
1possible duplicate of https://stackoverflow.com/questions/33021784/unset-session-when-browser-tab-is-closed and many other similar questions. For ref , check these as well: https://stackoverflow.com/questions/8311320/how-to-change-the-session-timeout-in-php https://stackoverflow.com/questions/24402047/php-session-destroy-after-closing-browser – user3532758 Apr 20 '22 at 00:01
2 Answers
Try something like this.
Client side (ie Javascript) you call a script every few seconds, let's say user_active.php.
Then user_active.php contain something like:
$last_seen = $_SESSION['last_seen'];
if (!$last_seen) {
$last_seen = time();
}
if (time() - $last_seen > 10) { // Will execute if the time elapsed is over 10 seconds
// Your code to execute if the user not active any more
}
else {
// Show user as still active
$_SESSION['last_seen'] = time(); // Update the last time checked
}
This code checks if the time was updated in the last 10 seconds. If the time was not updated it means the script is not being called from the client, meaning the user has closed the window.
Keep the file as "light" as possible, as it will be called repeatedly (and multiplied by the amount of concurrent users). Don't worry, the server can handle it, but no need to make it too heavy.

- 484
- 4
- 12
You can do a JS browser before unload check and post to a backend and destroy the session. I personally wouldn't. I would just set expired time on tokens.
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
// Axios post to logout session here.
});
Option Two:
app/session.php
'expire_on_close' => true
Only reason I put option one is because someone else may want to do other stuff on browser tab close.

- 3,339
- 2
- 14
- 35
-
Op doesnt ask to destroy sessions, is asking to get to know when user is loged out. **Is there a realistic way of knowing when the session of logged in user died ?** or session is expired. – Apr 20 '22 at 00:10