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

2023-01-19php开发问题
15

本文介绍了如何停止 AJAX 调用以保持 PHP 会话处于活动状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我的网站上有一个使用 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;
}

这篇关于如何停止 AJAX 调用以保持 PHP 会话处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17