html PHP自动注销,无需单击

f3temu5u  于 2022-12-09  发布在  PHP
关注(0)|答案(1)|浏览(119)

我尝试在我的php应用程序中实现一个在用户不活动10秒或更长时间后自动注销的功能。我的代码一切正常,唯一的问题是要注销,用户必须再次点击屏幕。我希望警告消息和注销在没有任何点击的情况下自动发生。下面是我的代码片段:

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>";   
    }
}
eivgtgni

eivgtgni1#

你需要做的就是调用一个函数,在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>

也可以将间隔设置为10000(10秒),这样就不需要经常检查了。一旦达到10秒,它就会退出。
但我认为您也希望,如果用户移动鼠标或单击某些内容,它不应该将他们注销,因为他们在页面上是活动。如果是这样,在setInterval函数之后,您可以添加,

<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>

更新自从这个答案发布后,很多事情都发生了变化。浏览器(特别是chrome)不再支持在后台运行javascript函数。这带来了一个问题,如果用户忙碌另一个标签,间隔停止运行。我强烈建议(我也将我的实现)移到webWorkers,以完成这个必须独立于您的应用程序在active选项卡上运行的任务。

相关问题