Search code examples
javascriptphphtmlxampp

PHP automatic logout without having to click


I'm trying to implement an automatic logout in my php application after the user has been inactive for 10 or more seconds. Everything works ok with my code, the only problem is that for the logout to be take place, the user has to click again on the screen. I want the alert message and logout to happen automatically without any clicks. Here's a snippet of my code:

if (isset($_SESSION['last_action'])) 
{
    //Figure out how many seconds have passed
    //since the user was last active.

    $secondsInactive = time() - $_SESSION['last_action'];    


    //Convert our minutes into seconds.

    $expireAfterSeconds = 10;   


    //Check to see if they have been inactive for too long.
    if($secondsInactive >= $expireAfterSeconds){
        //User has been inactive for too long.
        //Kill their session.
        echo "<script>
        alert('You have been logged out');
        window.location.href='../clinician/logout.php';
        </script>";   
    }
}

Solution

  • All you need to do is call a function runs in intervals in javascript

    <script language='javascript'>
      var timeout = 10 * 1000; // 10 seconds
      var lastAction = <?php echo isset($_SESSION['last_action']) ? $_SESSION['last_action'] : time();?>;
      setInterval(function(){
         var now = new Date();
         if (typeof lastAction !=='undefined' ){
             if(now.getTime() - lastAction >= timeout ){
                alert('You have been logged out');
                window.location.href='../clinician/logout.php';
             }
         }
      }, 1000) // repeat every 1 second;
    </script>
    

    and optionaly you can set your interval to 10000 (10seconds) and won't need to check constantly. once it hits that 10sec, it will logout.

    but also I think you will want that if user moves their mouse or clicks something it should not log them out since they are active on the page. if so after the setInterval function, you can add,

    <script language='javascript'>
      var timeout = 10 * 1000; // 10 seconds
      
      var lastAction = <?php echo isset($_SESSION['last_action']) ? $_SESSION['last_action'] : time();?>;
      var timer = function(){
         return setInterval(function(){
            var now = new Date();
            if (typeof lastAction !=='undefined' ){
              if(now.getTime() - lastAction >= timeout ){
                 alert('You have been logged out');
                 window.location.href='../clinician/logout.php';
              }
            }
          }, 1000) // repeat every 1 second;
      }
      window.onmousemove = function(e){
       clearInterval(timer);
       timer();   
      }
      window.onclick= function(e){
        clearInterval(timer);
        timer();
      }
    
      // and make initial call
      timer();
    </script>
    

    ** UPDATE ** Since this answer is posted, a lot of things have changed. Browsers ( especially chrome ) no longer support running javascript functions in the background if the tab is not active. This brings up the issue that if a user is busy with another tab, the interval stops running. I strongly suggest ( also I moved my implementations) to webWorkers for this job that has to run independently of your application on the active tab. For more information please refer to https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers