sg31
sg31

Reputation: 11

Destroy Session on Browser or Tab Close: Working for Firefox but not for Chrome

I have a requirement that after closing the browser when user open site it should ask for login by default.

I destroyed the session values on logout button so when user clicked on logout button it works fine but if user directly close the browser or tab the session are not destroying.

I have also tried to set session.cookie_lifetime value to 0 but its not working.

Upvotes: 1

Views: 831

Answers (2)

Bilaal Rashid
Bilaal Rashid

Reputation: 846

Browsers are an implementation of web standards. They have differences between them as to how they choose they decide to implement them and can sometimes differ from the standard.

If you set a session/temporary cookie, the idea should be that it will be deleted as soon as the website is closed. However, browsers don’t always follow this as gospel. They have convenience features which can keep the cookies and restore the user's session. This could be useful if the browser suddenly crashed or a user accidentally shut down the tab.

On the other hand, for developers, this creates meddling which is not how they should behave. This isn’t the sort of thing that can be controlled so you can’t really delete a cookie when a tab is closed. The only way to solve it is to store a timestamp in a session or another cookie and anytime a page is loaded, check to see if a reasonable timestamp has passed, after which case, the cookie could be destroyed. It’s not an ideal solution, but it is the only way to implement it in modern browsers.

Upvotes: 0

Lulceltech
Lulceltech

Reputation: 1702

The best way to do this in my opinion is the store the session with the time in it, you can create a javascript heart beat which will keep the time updated every x seconds and as look as now is never a larger time than time+x seconds then you will have your heart beat. If the time surpasses it the session will time out and you're off the the races.

On login:

session_start();
$_SESSION['last_action'] = time();

An ajax call every few (eg 20) seconds:

windows.setInterval(keepAliveCall, 20000);

Server side keepalive.php:

session_start();
$_SESSION['last_action'] = time();

On every other action:

session_start();
if ($_SESSION['last_action'] < time() - 30 /* be a little tolerant here */) {
  // destroy the session and quit
}

Upvotes: 1

Related Questions