Saturday, September 29, 2012

PHP session keep-alive: JavaScript solution

PHP session keep-alive mechanism, client side with JavaScript.

*** File: page.html

<script type="text/javascript" src="keep-alive.js"></script>


*** File: keep-alive.js

function KeepAlive() {
   
    // Keep alive session time (seconds)
    this.nKeepAliveSeconds = 4 * 60 * 60;
   
    // Keep alive time interval to check elapsed time (seconds)
    this.nKeepAliveTimeIntervalCheck = 60;
   
    // Keep alive time interval to call the AJAX keep-alive server file (seconds)
    this.nKeepAliveTimeInterval = 8 * 60;
   
    // unix timestamp when the page was first loaded
    this.nKeepAliveTimestampStart = 0;
   
    // unix timestamp when the session was last refreshed
    this.nKeepAliveTimestampLast = 0;
   
    this.init = function() {
        this.nKeepAliveTimestampStart = Math.round((new Date()).getTime() / 1000);
        this.nKeepAliveTimestampLast = this.nKeepAliveTimestampStart;
    }
   
    this.run = function() {
        var nTimestampNow = Math.round((new Date()).getTime() / 1000);
       
        if(nTimestampNow > this.nKeepAliveTimestampLast + this.nKeepAliveTimeInterval) {
            this.ajaxCall();
            this.nKeepAliveTimestampLast = nTimestampNow;
        }
       
        if(nTimestampNow < this.nKeepAliveTimestampStart + this.nKeepAliveSeconds) {
            setTimeout("KeepAlive1.run()", this.nKeepAliveTimeIntervalCheck * 1000);
        }
    }
   
    this.ajaxCall = function() {
        $.get("/keep-alive.php", function(data) {});
    }
   
}

var KeepAlive1 = new KeepAlive();
KeepAlive1.init();
KeepAlive1.run();

*** File: keep-alive.php

<?php

session_start();
echo 'Keep-alive: ' . time();

?>

No comments: