-1

I have a small chat website with only one page. I save all the data in session when user logs in. Session is deleted when user logs out through a logout button. But if user closes the page and comes back in like 5 minutes, he is still logged in, thus session is still active and I don't want that.

zalaw
  • 33
  • 1
  • 3
  • Decide on how long the session will last before it expires, and timestamp it, then use that timestamp as part of your query to decide whether the user still has an active chat. – droopsnoot May 03 '20 at 17:34
  • Does this answer your question? [How do I expire a PHP session after 30 minutes?](https://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes) – JeffUK May 03 '20 at 20:24
  • Welcome to Stack Overflow! If you are using Sessions: You need to handle the cookies on your browser, and handle sessions on the PHP side, it is highly recommended to use JWT(JSON Web Token) – Ebrahim May 04 '20 at 16:02

2 Answers2

0

There's a beacon request in modern browsers that sends a request when a tab / windows is gonna be closed and guarantees its delivery (it won't be cancelled).

With its help you can send a request to terminate a session.

More info you can read here: https://developer.mozilla.org/en-US/docs/Web/API/Beacon_API/Using_the_Beacon_API

window.onunload = function analytics(event) {
  if (!navigator.sendBeacon) return;

  var url = "https://example.com/analytics";
  // Create the data to send
  var data = "state=" + event.type + "&location=" + location.href;

  // Send the beacon
  var status = navigator.sendBeacon(url, data);

  // Log the data and result
  console.log("sendBeacon: URL = ", url, "; data = ", data, "; status = ", status);
};

A usual implementation - to send a ping request every N seconds and store the timestamp of the last request in the session. When session starts to check its timestamp with current one and unset current session's variables if it differs more than 2-3 timeframes.

satanTime
  • 12,631
  • 1
  • 25
  • 73
-1

Here are some answers for your problem:

Unset Session When browser tab is closed

PHP - Session destroy after closing browser

But you can send frequent ajax requests to the server to keep the session and if within 10 second there was no ajax request, you unset session

setInterval(() => {
    // ajax requset
}, 1000)
reza moradi
  • 17
  • 1
  • 5