dpwqicw157673 2012-07-09 11:07
浏览 38
已采纳

PHP会话超时脚本[重复]

This question already has an answer here:

I have this code that logs a user out if they don't change pages for 10 minutes.

$inactive = 600;

if(isset($_SESSION['timeout']) ) {
  $session_life = time() - $_SESSION['timeout'];
  if($session_life > $inactive) { 
    header("Location: logout.php"); 
  }
}

$_SESSION['timeout'] = time();

As you can see it's pretty straightforward. I include this function at the top of all my protected pages and if the script isn't run for 10 minutes, the next time you refresh the page, the user is sent to my logout script.

However that's the problem. After $session_life > $inactive becomes true, the script needs to be run again for the user to be logged out. I need the person to be immediately logged out as soon as this becomes true.

Is there any way to do this without things getting too complicated? (i.e. not using AJAX)

</div>
  • 写回答

4条回答 默认 最新

  • dongniechi7825 2012-07-09 11:10
    关注

    No. Your PHP code runs on every request. If you want the timeout to trigger "immediately" then you have to either spam the server with continuous requests (bad idea) or move the timeout logic to client-side code.

    An appropriate solution could be to start a Javascript timer when the page loads and redirect the user to the logout page when the timer expires. If the user navigates to another page in the meantime the current timer would be discarded automatically and a new one started when that page loads. It can be as simple as this:

    <script type="text/javascript">
        setTimeout(function() { window.location.href = "logout.php"; }, 60 * 10);
    </script>
    

    Update: Of course, you should also keep the server-side code to enforce the business rule on your own side. The Javascript will give you an "optimal" scenario when the client side cooperates; the PHP code will give you a guarantee if the client side works against you.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加