且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP会话超时脚本

更新时间:2023-12-04 20:01:10

否.您的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.