Thursday, March 8, 2018

How to keep a user's session alive

There may be instances where you need to keep a user's session alive. For example, your visitors need to take an hour long course, but the global session timeout is 30 minutes. You don't want the user's session to time out before they finish the course, right?

Here is a simple way to keep the session alive.

Add this script to the very top of the pages. Then, add a blank page in the same directory. Notice the bold red line below - I have a 'keep_alive.cfm" file in the same directory, which is accessed by the script which in turn keeps the session alive.

<script>
    var xmlhttp;
setInterval
    (
        function() {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            } else {
                // code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open("POST", "keep_alive.cfm", true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlhttp.send("foo=bar");
        }, 60000
); // 1 minute
</script>



Enjoy!

No comments:

Post a Comment