I consider two scenarios:
And here I do not know, what should I do. There is a event: window.onunload
which can be used perhaps like this (not tested):
<script>
var logout_php = function () {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "logout.php", true);
xhttp.send();
}
window.onunload = logout_php ;
</script>
But when the user opens more tabs and closes just one of them, he will be logged out. Probably it will log out even, when somebody refreshes the same page.
I considered to count all opened tabs with the same domain address, and if there is only one left, then will be the final logout. But this is not possible, because you can not access another windows (tabs) opened in browser.
I am sure, it must be a common problem, but I can not find appropriate answer.
thanx
Sessions are used to handle these kind of things. If you logout then your session is destroyed and if someone closes the window directly then in that case their session is destroyed as well. So, as long as you are using sessions, there is nothing to worry about.
You can try a keep_live ajax function that calls your server every 1 minute or so updating the last_checkin variable in database or so. If the tab is closed, said function is no longer being called.
In the beginning of every request check if last_checkin is within the last minute (+ some time for connection). If not, redirect to log out (and destroy session if it exists).
This is similar to session timeout. You can have this done every 5 seconds or so. If someone closes his tab and then (for some weird reason) someone else sits on the PC and opens previously closed tabs. Most likely the x time has passed since last check in and user is now logged out.
The down side is the traffic between user and server but it's not a big deal. This is how you check for chat updates anyway so it is done in many services.