如何停止 AJAX 调用以保持 PHP 会话处于活动状态

2021-12-21 00:00:00 php javascript ajax cakephp

我的网站上有一个使用 CakePHP 的身份验证系统.为此,它使用了 PHP 会话.

I have an authentication system on my site using CakePHP. It uses PHP Sessions for this.

我有一个 AJAX 调用(在每分钟运行一次的 setInterval 内)到一个检查用户是否仍然登录的函数.如果它返回 false,那么 Javascript 将获取当前 URL 并尝试重定向它们,这又会将它们重定向到登录页面.从理论上讲,这是有效的,因为它主动要求用户重新登录,而不是举行一个陈旧的会话,这只会要求他们在点击某物后立即登录.我的问题是我的 AJAX 调用使会话保持活动状态.所以永远不要退出(我们不想要)

What i have in place is an AJAX call (within a setInterval running every minute) to a function which checks if the user is still logged in. If it returns false, then the Javascript takes the current URL and attempts to redirect them, which in turn redirects them to the login page. In theory this works because it actively asks the user to re-login instead of holding a stale session which will just ask them to login as soon as they click something. My problem is that my AJAX call is keeping the session alive. So never get logged out (which we don't want)

我可以在 CakePHP 中做些什么或我可以使用任何其他方法来阻止这种情况发生吗?

Is there ANYTHING i can do within CakePHP or any other methods i can use to stop this happening?

推荐答案

当您检查会话的有效性时,将 &ajax=(任何内容)添加到查询字符串中.

Add &ajax= (anything) to the query string when you're checking for the validity of the session.

>

然后,更改您的 PHP 会话代码:

Then, alter your PHP session code:

session_start();
if(!isset($_GET["ajax"])) $_SESSION["lastactivity"] = time();
if(now() - $_SESSION["lastactivity"] > 3600){ //3600 seconds
    header("Location: login.php?url="+urlencode(str_replace("&ajax=", "", $_SERVER["REQUEST_URI"])));
    //Example:
    // Location: login.php?url=/sensible/secret.php?mode=show&hide=nothing
    exit;
}

相关文章