PHP会话超时脚本 [英] PHP session timeout script

查看:84
本文介绍了PHP会话超时脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码可以让用户在10分钟内不更改页面的情况下将其注销.

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();

如您所见,它非常简单.我在所有受保护页面的顶部都包含此功能,如果脚本未运行10分钟,则下次您刷​​新页面时,会将用户发送到我的注销脚本.

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.

但这是问题所在.在$ session_life> $ inactive变为true之后,需要再次运行该脚本以使用户注销.我需要尽快将这个人注销.

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.

有什么办法可以做到,而又不会使事情变得太复杂? (即不使用AJAX)

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

推荐答案

否.您的PHP代码会在每个请求上运行.如果要让超时立即"触发,则必须要么用连续的请求向服务器发送垃圾邮件(不好的主意),要么将超时逻辑移至客户端代码.

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.

一种适当的解决方案是在页面加载时启动Javascript计时器,并在计时器到期时将用户重定向到注销页面.如果在此期间用户导航到另一页面,则当前计时器将自动丢弃,并在该页面加载时开始新的计时器.可以这样简单:

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>

更新:当然,您还应该保留服务器端代码以自行执行业务规则.当客户端合作时,Javascript将为您提供最佳"方案;如果客户端对您不利,PHP代码将为您提供保证.

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.

这篇关于PHP会话超时脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆