I have a PHP application that stored the session ID of a user upon login in a MYSQL table, which is removed when the user logs out and their session is destroyed through the logout process. the User is not allowed to log in again if the MYSQL table still has a value in that session_id column. This works great in case of naturally triggered logouts. However when the user simply closes the browser window/tab, it seems that the server is retaining the session variables and moreover since the natural logout.php was not invoked the session_id column in the MySQL table is also not getting emptied out. AS a result, I can type in any of the URLs that are protected by the login from the same computer and get right in. This is a security issue - triggered by a user who did not follow the instructions of logging out naturally instead of just closing the browser window.
I have followed the SO thread here and have tried to use the onbeforeunload() JS function to handle this situation of a browser close. As you know the onbeforeunload() event gets triggered when any of these 4 events occur - (1) browser close (2) navigating away from the page to another page by clicking on a "" link (3) refreshing the page (4) submitting a form.
In the code below I am having the following problems in (1) and (3) and I am having a hard time figuring it out : Prob 1. When I close the browser window, I get that alert with "Stay On the Page " and "Leave Page" options. However that AJAX call to call_my_special_script.php is occurring on both options, when it should not occur in case of "Stay On The Page". call_my_special_script.php simply removes the contents of the session_id in the MySQL table. Prob 2. When I refresh the browser - Safari / IE the code says nothing should happen, but I am getting that alert show up when I am not expecting it. Regardless of my choice on the alert it is calling call_my_special_script.php and removing the session_id value.
Any ideas what I should be doing here to fix these problems?
<script>
var validNavigation = false;
function browserCloseEvents() {
var dont_confirm_leave = 0;
var leave_message = 'You sure you want to leave the page?'
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave!==1) {
if(!e) e = window.event;
e.cancelBubble = true;
e.returnValue = leave_message;
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
$.ajax({
type: 'GET',
url: "call_my_special_script.php",
async: false,
success: function () {
alert("sucess");
}
});
return leave_message;
}
}
}
window.onbeforeunload = goodbye;
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
$("a").bind("click", function() {
validNavigation = true;
});
$("form").bind("submit", function() {
validNavigation = true;
});
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
}
$(document).ready(function() {
browserCloseEvents();
});