Home > front end >  How can I know when the user logged out by closing the browser tab in php?
How can I know when the user logged out by closing the browser tab in php?

Time:04-20

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

CodePudding user response:

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.

CodePudding user response:

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.

Option one: https://www.geeksforgeeks.org/how-to-detect-browser-or-tab-closing-in-javascript/#:~:text=A tab or window closing,the tab or the browser.

    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.

  • Related