I have users login/logout application: I want to destroy session, its working fine when I close the browser (( all tabs )) , IE , Firefox working. But I want to destroy the session when user close the single tab . I am using :
session_set_cookie_params(0);
session_start();
Browsers only destroy session cookies when the entire browser process is exited. There is no reliable method to determine if/when a user has closed a tab. There is an onbeforeunload
handler you can attach to, and hopefully manage to make an ajax call to the server to say the tab's closing, but it's not reliable.
And what if the user has two or more tables open on your site? If they close one tab, the other one would effectively be logged out, even though the user fully intended to keep on using your site.
Solution is to implement a session timeout with own method. Use a simple time stamp that denotes the time of the last request and update it with every request:
You need to code something similar to this
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// request 30 minates ago
session_destroy();
session_unset();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time
More about this you can found here which is similar to your question Destroy or unset session when user close the browser without clicking on logout.
It covers all you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With