7
Session Timeout Warning PHP Example with jQuery/JS
Web development, jquery, php
Tags: browser, php
Share
Updated 11-Jan-2010: Improved ability to adjust timeouts and simplified code a bit.
Detecting and warning a user of their session timing out can come in handy and, in some cases, may be necessary. Here is one way of doing this with jQuery/javascript and PHP. There may be a better way to do this, so take this as an example.
There is a post on a ColdFusion session timeout warning that works in a similar manner.
Session Defined: Start to Finish
A session is defined as when a user begins and ends using or visiting a web site. It can be unlimited in length or strictly defined by a timeout period. If the site requires a log in or accesses sensitive data, it should time out after a period of inactivity. They can end a session by logging out or closing the browser.
Inactivity means the user has done nothing, made no requests of the web server, during a specified time. Ajax requests usually do not count. There are other posts out there that detail how to check for session expiration with Ajax requests.
Demo
The session time left is determined by the server, and, if you want to poll the server with an Ajax request, go for it. This demo uses javascript to keep track of the time left in the session.
The demo uses a simple log in with session timing handled by jquery and javascript. When the session expiration approaches, the user is warned and given an opportunity to restart the session. If the session time limit is reached, the user is prompted to log in again. If they ignore that prompt, the page automatically redirects to the log in form. In the demo this sequence of events takes 40 seconds to complete and is broken down as follows:
- Session timeout: 30 seconds
- Timeout warning: 20 seconds
- Session expired warning: 10 seconds
- Redirect to log in page: 10 seconds
Interrupting the User
The user’s attention can be diverted away from other open windows to the eminent session expiration by using a javascript alert in place of the jquery dialog box. Personal preference.
Code Breakdown
The log in page checks for a query string variable called ‘expired’ and sets the loggedin cookie to false. This is there because the code is going to control the expiration of the session eliminating the need to compensate for browser latency. The actual session start time the time the page loads can differ by several seconds. To avoid having to add time to the session or any other fancy guesswork, when the allotted session time has expired according to the javascript timer on the page, they are done – session over.
If they are logged in, they get bumped to the index page. The rest is the logic that handles the log in form.
Note: I would not recommend handling a log in form this way. This is for demonstration only.
//if query string contains expired var & it = true, set loggedin cookie as false
//else if loggedin cookie exists and is set to true, send to index page
if (isset($_GET['expired']) && $_GET['expired'] == 'true')
{
setcookie("loggedin", "false", time()+30);
}
elseif (isset($_COOKIE['loggedin']) && $_COOKIE['loggedin'] == 'true')
{
header("Location: index.php");
exit;
}
//log in logic
if (isset($_POST['username']) && isset($_POST['pw']) && $_POST['username'] == "session" && $_POST['pw'] == "test")
{
setcookie("loggedin", "true", time()+30);
header("Location: index.php");
exit;
}
Other than the log in form and a message for the user, that’s all there is to the log in page.
Handling Session Timeout
The index page handles the session timeout code. This could be a separate javascript included in every page. The first block simply determines if they are logged in. If they are not, send them to the login page. If they are, refresh the cookie timeout by resetting it.
if (!isset($_COOKIE['loggedin']) || (isset($_COOKIE['loggedin']) && $_COOKIE['loggedin'] == 'false'))
{
header("Location: login.php");
exit;
}
elseif (isset($_COOKIE['loggedin']) && $_COOKIE['loggedin'] == 'true')
{
//user is logged in, page was refreshed or reloaded to restart session so reset cookie
setcookie("loggedin", "true", time()+30);
}
?>
Now the time variables are set and the a javascript timer is set to check the session every 10 seconds.
Javascript uses milliseconds so for clarity the time intervals multiply the number of seconds by 1,000. You could put 10000 in for 10 seconds but I think 10*1000 helps me determine that it is 10 seconds quite a bit faster. Do what is comfortable for you.
Also, a flag is set to determine if the warning dialog box has been opened and the countdown has begun.
//event to check session time variable declaration
var checkSessionTimeEvent;
$(document).ready(function() {
//event to check session time left (times 1000 to convert seconds to milliseconds)
checkSessionTimeEvent = setInterval("checkSessionTime()",10*1000);
});
//Your timing variables in number of seconds
//total length of session in seconds
var sessionLength = 30;
//time warning shown (10 = warning box shown 10 seconds before session starts)
var warning = 10;
//time redirect forced (10 = redirect forced 10 seconds after session ends)
var forceRedirect = 10;
//time session started
var pageRequestTime = new Date();
//session timeout length
var timeoutLength = sessionLength*1000;
//set time for first warning, ten seconds before session expires
var warningTime = timeoutLength - (warning*1000);
//force redirect to log in page length (session timeout plus 10 seconds)
var forceRedirectLength = timeoutLength + (forceRedirect*1000);
//set number of seconds to count down from for countdown ticker
var countdownTime = warning;
//warning dialog open; countdown underway
var warningStarted = false;
The checkSessionTime function is what gets fired off every 10 seconds by the timer. It does a time comparison and opens the dialog boxes that warn the user.
function checkSessionTime()
{
//get time now
var timeNow = new Date();
//event create countdown ticker variable declaration
var countdownTickerEvent;
//difference between time now and time session started variable declartion
var timeDifference = 0;
timeDifference = timeNow - pageRequestTime;
if (timeDifference > warningTime && warningStarted === false)
{
//call now for initial dialog box text (time left until session timeout)
countdownTicker();
//set as interval event to countdown seconds to session timeout
countdownTickerEvent = setInterval("countdownTicker()", 1000);
$('#dialogWarning').dialog('open');
warningStarted = true;
}
else if (timeDifference > timeoutLength){
//close warning dialog box
if ($('#dialogWarning').dialog('isOpen')) $('#dialogWarning').dialog('close');
$('#dialogExpired').dialog('open');
//clear (stop) countdown ticker
clearInterval(countdownTickerEvent);
}
if (timeDifference > forceRedirectLength)
{
//clear (stop) checksession event
clearInterval(checkSessionTimeEvent);
//force relocation
window.location="login.php?expired=true";
}
}
The countdownTicker function provides a countdown inside the warning dialog box to prompt the user to act now. It uses a timer that fires every second for a 5,4,3,2,1 effect inside the dialog box.
function countdownTicker()
{
//put countdown time left in dialog box
$("span#dialogText-warning").html(countdownTime);
//decrement countdownTime
countdownTime--;
}
And, the dialog boxes either allow the user to reload the page or, if they did nothing when the warning popped up, it logs them out by redirecting to the log in page with the expired variable in the query string. Also, thanks to scube’s debugging, it now redirects to the log in if they hit the close button on the dialog box rather than the Login button.
$(function(){
// jQuery UI Dialog
$('#dialogWarning').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: {
"Restart Session": function() {
location.reload();
}
}
});
$('#dialogExpired').dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
close: function() {
window.location="login.php?expired=true";
},
buttons: {
"Login": function() {
window.location="login.php?expired=true";
}
}
});
});
The dialog box contents are at the bottom of the page but they could be just about anywhere in the body.
<!--Dialog box contents--> <div id="dialogExpired" title="Session (Page) Expired!"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Your session has expired!<p id="dialogText-expired"></p></div> <div id="dialogWarning" title="Session (Page) Expiring!"><p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 0 0;"></span> Your session will expire in <span id="dialogText-warning"></span> seconds!</div>
Remember, this is just one example. There are other ways to do this. Use this, improve this, or roll your own.
Usual recommended jQuery and PHP reading:
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.
No related posts.
24 Comments for Session Timeout Warning PHP Example with jQuery/JS
Hey…its an amazin script whiich i’ve found after lot of googlin on net……read 1000s of scripts but its wonderful…..wanted to knw if u’ve any script in php to avoid multiple logins from same user account….plz post if thr’s any….
@Shelly
Multiple logins from the same account can be handled by a check to a database that holds the last login and either flags it as logged out or deletes it when the user logs out.
It can be as simple as just having a userid field in a table, inserting the userid when they log in and deleting it when the log or time out. If their userid is in the table when they log in, disallow the log in.
fauzi
October 2, 2009
very good code. i love it
jack
October 21, 2009
Hi, I would like to thank you for this awesome example. It is exactly what I was looking for. I really aprreciate your effort. Many thanks!
henry
October 27, 2009
Thanks a lot.
Hi, wonderful script!
But I found a bug, you can hit the cross in the upper right corner to close the dialog. If you do that nothing happens. Maybe ther can be implemented a close-callback to redirect to the login page.
@scube
Thank you. I will look into the dialog close button issue and post any updates I come with.
I added the following pice of code to the expired dialog:
close: function(event, ui) {
window.location=”/index.php?expired=true”;
},
I just implemented it in my application on http://www.mailexpert.ch – check it out
@scube
Yep, that’s correct.
You could leave out the function params:
close: function() { window.location=”login.php?expired=true”;
}
Will update the post. Thank you!
Jim
November 20, 2009
Jen, Thank you for the timeout script.
When a page expires a reload is done to prevent timeout. However, If the person is in the middle of filling out a form, all form data entered is lost with the reload.
I’ve modified your script a bit and rearranged things a little to make it more “form” friendly.
I changed the script to remove the dialog box and reset time variables rather than do a reload. Also, changed it so that communication between javascript and php is done via $_COOKIE, rather than use $_GET to signal page expiration. This is a little more friendly toward using Zend Framework.
Also moved the expire code into the countdownTicker function. this assures that the page expires when the dialog box counts down to 0, and not when checkSessionTime() runs and determines that the page needs to expire. The dialog box may indicate that the page will expire in 2 or 3 seconds and poof, page reloads.
Your script was a great starting point. Thank you all your work and sharing. If you would like the script as I’ve modified it let me know and I’ll send it to you. You can share it with your readers if you like.
All the best,
jim
@Jim
Glad the script helped out. It was meant only to be a starting point as you mentioned.
Thank you for sharing the suggestions and modifications.
I would love to look at your script. You can email me at jen (at) jensbits.com
If I work it into a post, I’ll give you the credit.
Shelly
November 21, 2009
Hi Jim…it wud b gr8 if u can share the modified script with us…if possible mail me at shelly_aggin@yahoo.co.in
Updated the code.
Jared
February 25, 2010
Jen, Great code example. I am having an odd bug when deploying something similar. I keep getting a $("#dialogWarning").dialog is not a function error. I know it has something to do with jquery.. But I am not sure what at this point..
@Jared
Can you send me a test link?
Jared
February 26, 2010
Thanks for your response Jen. I figured it out… I Had not properly setup the ui js file.
Again, great work! I have one more question.. If I setup the main scripts on a page that then uses a iframe to access other pages… would the cookie appropriately update if every new page reset the cookie… Or would I need to add the js to every page so they would operate independently??? Thanks in advance
@Jared
Glad you got the other issue worked out.
I think you are talking about the time to expire being reset because if they are sitting on a page that loads iframe content, that page could expire.
So, no, the cookie updating really isn't the main mechanism here. It's the checkSessionTime function. The cookie just keeps track of whether or not they are logged in with a true/false value.
I haven't put this in an iframe so I don't know how it will react.
PanYaung
February 28, 2010
Hi Jen, Thanks for your script. It's really useful for me. May I get the updated script as Jim mentioned coz I also don't want to restart session while filling in the form. Thanks in advance!
@Pan Yaung
I don't have the code Jim sent me anymore. He outlines what he did very well. Just follow his suggestions.
PanYaung
March 1, 2010
Hi Jen, thanks for your response. I've changed the button for warning dialog box to 'Back to page' and in the function I added the following:
('#dialogWarning').dialog('close'); warningStarted=false; pageRequestTime = new Date();
Form is not reloaded after clicking the button but when the warning dialog box displayed on the next session time out, the time left didn't display 10,9,8,… and it displayed -21, -23, -25, and so on..
I don't have an idea where should I change and still trying to figure out. If you have any idea, pls share me.
Thanks again ![]()
PY
@PY
You may need to reset the
var warning = 10;
when you reset the pageRequestTime variable.
PanYaung
March 1, 2010
I've also tested by reseting waring=10 too. But still can't. I'll try that again.
Dan Wasson
March 4, 2010
thank you for posting this! also, if you haven't seen it already, you might like :
http://plugins.jquery.com/project/jquery-activity-plugin
This is useful article., its nice posting. good job.
Thanks a lot..!
Leave a comment
« [Discussion] Donating to Developers: It’s the Right Thing to Do | ColdFusion Example: Session Timeout Warning with jQuery/JS »

Shelly
September 17, 2009