Web application session timeout code
Session timeout warning for a web application with a variety of page layouts and frequent use of multiple tabs.
Nutshell explanation - ping the server, if you get a 403, show a huge red bar across the top of whatever page pinged.
Result:
- It is immediately apparent the tab has timed out
- If one tab times out, it does not disrupt the others
- There is a link to help the user log in again
function sessionPing() {
var pinger;
function doPing() {
var pReq = new XMLHttpRequest();
pReq.addEventListener("load", function () {
var sessionExpired, sessionExpiredMessage;
var reloadLink;
if (this.status === 403) {
clearInterval(pinger);
sessionExpired = document.createElement("div");
// Sometimes an inline style is really the best solution
sessionExpired.setAttribute("style","display:block; width: 100%; line-height: 2.5em; position:absolute; top:0; z-index:10000; text-align: center; background-color: #f00; color: #fff; font-family: 'Trebuchet MS',sans; font-size: 1.5em; font-style: italic");
sessionExpiredMessage = document.createTextNode("Session expired ");
sessionExpired.appendChild(sessionExpiredMessage);
reloadLink = document.createElement("a");
reloadLink.href = location.href;
reloadLink.textContent = "Click to Continue";
reloadLink.setAttribute("style","font-size:0.7em;color:#ddd");
sessionExpired.appendChild(reloadLink);
document.body.insertBefore(sessionExpired, document.body.firstChild);
document.title = "Session expired";
}
});
pReq.open("GET", "/ping.php");
pReq.send();
}
pinger = setInterval(doPing, 30000);
}
sessionPing();
<?php
session_start();
if (empty($_SESSION['user_id'])) {
header('HTTP/1.1 403 Forbidden');
exit;
}
header('HTTP/1.1 201 No content');
exit;
One may argue that the page should be cleared, in this case, I chose to leave it up so people can copy the content off.
Confession: I didn't test this code, it is an extract.
This post courtesy of Game Creek Video
Print article | This entry was posted by elvis on 08/28/17 at 09:01:00 pm . Follow any responses to this post through RSS 2.0. |