destroy session when broswer tab closed
Solution 1
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 2
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.
beginner web developer
Updated on September 19, 2020Comments
-
beginner web developer over 3 years
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();
-
beginner web developer almost 12 yearsbut
onbeforeunload
also working when user refresh the page , I want to destroy the session when user close the browser or close the tab -
Fabrício Matté almost 12 yearsYou've covered in detail every point I was about to comment before I even finished the comment, very well done.
-
Marc B almost 12 years@beginnerwebdeveloper: Like I said, you can't do this 100% reliably.
-
Quentin over 5 yearsThis doesn't address the "when the tab is closed" part of the question