Revised code
This code will make reference to the example I wrote available here >> jquery-idle with jquery-ui Dialog
Libraries used :
Embedded Library Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://thorst.github.io/jquery-idletimer/prod//src/idle-timer.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
Without jQuery dialog :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://thorst.github.io/jquery-idletimer/prod//src/idle-timer.js"></script>
Please keep in mind that you may switch out the dialog code with whatever your prefered dialog method is. I included jquery-ui for dialog to keep things as simple as possible. This also does not handle the beforeunload
event, as you have that covered in your code, however I would suggest read further here >> beforeunload stackoverflow article <<
Explanation
HTML
This line of code is for the placeholder where the countdown timer will be stored. To simplify things, I also use this when the timer has expired to display "Session Expired"
<div id="sessionSecondsRemaining" style="font-size: 22px; font-weight: bolder;"></div>
This is a very simple Modal dialog using jQuery UI. You can expand on it or replace it at your leisure.
<div id="dialog-confirm" title="Logout" style="display: none;">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;">Your session has expired.</span></p>
</div>
Without jQuery Dialog
<div id="sessionSecondsRemaining" style="display:none;"></div>
CSS
This is just a small hack due to a bug in the grayed background not displaying properly for jQuery UI modal dialogs (why has this not been fixed yet -- facepalm )
/* override jquery ui overlay style */
.ui-widget-overlay {
background-image: none !important; /* FF fix */
background: #000 url(images/new-ui-overlay.png) 50% 50% repeat-x;
}
Without jQuery Dialog
Javascript
This section is where you can configure the parameters for jquery-idletimer.
var
session = {
//Logout Settings
inactiveTimeout: 10000, //(ms) The time until we display a warning message
warningTimeout: 10000, //(ms) The time until we log them out
minWarning: 5000, //(ms) If they come back to page (on mobile), The minumum amount, before we just log them out
warningStart: null, //Date time the warning was started
warningTimer: null, //Timer running every second to countdown to logout
logout: function () { //Logout function once warningTimeout has expired
//window.location = settings.autologout.logouturl;
},
//Keepalive Settings
keepaliveTimer: null,
keepaliveUrl: "", // set the Keep Alive URL here (aka keepalive.php)
keepaliveInterval: 5000, //(ms) the interval to call said url
keepAlive: function () {
$.ajax({ url: session.keepaliveUrl });
}
}
;
To add 'keepalive.php' support, simply set the full URL for where keepalive.php is located (and any parameters you wish to pass, since you are using sessions, you shouldn't need any).
keepaliveUrl: "http://example.com/keepalive.php", // set the Keep Alive URL here (aka keepalive.php)
This line, initializes and sets the value in the #sessionSecondsRemaining
div.
$('#sessionSecondsRemaining').html(Math.round((session.warningTimeout - diff) / 1000));
This section is where you would put the code that controls your dialog warning the user of a session expiration countdown (usually #sessionSecondsRemaining would be in this dialog)
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Extend": function() {
clearTimeout(session.warningTimer);
$( this ).dialog( "close" );
},
Cancel: function() {
session.logout();
$( this ).dialog( "close" );
}
}
});
Without jQuery Dialog
If you notice, 'Extend', terminates the warning timer, and Cancel calls the logout function (also configurable above)
Lastly, this block is very important to what happens in the event the timer counts down to zero, and for controlling the display of the countdown inside #sessionSecondsRemaining
if (remaining >= 0) {
$('#sessionSecondsRemaining').html(remaining);
} else {
$( '#dialog-confirm' ).dialog( "close" );
clearInterval(session.warningTimer);
$( '#sessionSecondsRemaining' ).html('Session Expired');
session.logout();
}
Under the else
, is probably the only spot you will really need to modify in the above block. In there, I call the session.logout()
function (should really be the last line after dialogs are cleaned up, but this is just a demo). This is where you close the dialogs, and/or redirect the user to the session expired page, or display the message. If staying on the same page, make sure to clearInterval(session.warningTimer);
. If not, then that line does not matter.
Without jQuery Dialog
if (remaining >= 0) {
$('#sessionSecondsRemaining').html(remaining);
} else {
clearInterval(session.warningTimer);
session.logout();
}
keepalive.php
if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
include 'db.php';
$maxtimeout = 15; // Seconds for max timeout before forcing session reset on other users.
mysql_query("UPDATE users SET status = 1 WHERE user_id = ".$_SESSION['user_id']."");
mysql_query("UPDATE users SET status = 0 WHERE user_id <> ".$_SESSION['user_id']." AND (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`timestamp_field`)) > " . $maxtimeout . "";
This task should be set to run server-side to cleanup the database from any strays (if you have a lot of activity, then you won't need this script)
cron.php
include 'db.php';
// Set this for a longer timeout than in keepalive.php
$maxtimeout = 90; // Seconds for max timeout before forcing session reset on other users.
mysql_query("UPDATE users SET status = 0 WHERE (UNIX_TIMESTAMP() - UNIX_TIMESTAMP(`timestamp_field`)) > " . $maxtimeout . "";