【问题标题】:PHP Session never ends because ajax callsPHP 会话永远不会结束,因为 ajax 调用
【发布时间】:2013-05-30 18:18:48
【问题描述】:

我有一个使用 ajax 并每 10 秒执行一次以更新一些数据的网络应用程序。 我设置了一个 PHP 会话,在 60 分钟不活动后 php 会话终止并将用户踢出页面,但在此页面中会话永不过期,我猜这是因为 Ajax 调用每 10 秒执行一次,服务器刷新“超时”,我的会话在我不执行 ajax 的其他页面上运行良好。你们认为我在这个页面中的问题是因为 ajax 每 10 秒调用一次?

我的 Jquery 代码:

    delay(function(){
        check();
    }, 10000 );

    function check()
    {
      $.ajax({
        dataType: "json",
        url: "lead.php",
        cache: false,
        success: function(msg){
            //Do something
        }
      });
     }

【问题讨论】:

  • 当然,您已经回答了自己的问题。如果问题只出在有ajax的页面上,并且如果它每10s发送一次请求,它真的会重置超时。您可以通过手动跟踪会话超时来解决此问题。
  • 根据您对情况的描述,您对问题的评估似乎是准确的。您有什么问题需要我们帮助您解决吗?
  • 感谢您的帮助。如何继续跟踪会话,或者如何在 30 分钟不活动后终止会话?
  • @Aneri 我很想知道 php 页面是如何知道请求来自哪里的。 http 标头中是否包含 cookie 或其他跟踪设备?
  • lead.php 是否返回了一些机密数据?如果没有,请尽量不要在此页面上开始会话或使用 Aneri 的答案。

标签: php jquery


【解决方案1】:

如果您想在 X 时间后关闭会话,无论是否发出 ajax 请求,但前提是用户在页面上没有活动,您可以使用我正在使用的这段代码:

(function () {
    // After 30 minutes without moving the mouse, the user will be redirect to logout page
    var time2refresh = 30;
    // This is how many time the user has to be inactive to trigger the countdown of 30 minutes
    var timeInactive = .5;
    // This will store the timer in order to reset if the user starts to have activity in the page
    var timer = null;
    // This will store the timer to count the time the user has been inactive before trigger the other timer
    var timerInactive = null;
    // We start the first timer. 
    setTimer();
    // Using jQuery mousemove method 
    $(document).mousemove(function () {
            // When the user moves his mouse, then we stop both timers
        clearTimeout(timer);
        clearTimeout(timerInactive);
            // And start again the timer that will trigger later the redirect to logout
        timerInactive = setTimeout(function () {
            setTimer();
        }, timeInactive * 60 * 1000);
    });
    // This is the second timer, the one that will redirect the user if it has been inactive for 30 minutes
    function setTimer() {
        timer = setTimeout(function () {
            window.location = "/url/to/logout.php";
        }, time2refresh * 60 * 1000);
    }
})();

所以这个函数的逻辑是这样的:

1) 用户登录您的网站 2) 0.5 分钟(30 秒)不活动后,将开始 30 分钟倒计时 3) 如果用户移动他的鼠标,两个定时器都被重置,第一个定时器重新开始。 4) 如果用户在 30 分钟后没有移动鼠标,那么它将被重定向到注销页面,关闭他的会话。

【讨论】:

  • 很棒的代码,我想我会使用你的代码,但我将使用 .click 事件而不是鼠标悬停。
  • @HelderAlvarez 不要忘记将此标记为解决方案 ;)
【解决方案2】:

我猜lead.php 使用session_start()。您只能在该文件中删除它。

或者,在第一次初始化时,将当前时间保存到会话变量中,然后对于每次调用,检查是否超过一小时。如果为真,session_destroy()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2021-05-17
    • 2013-04-09
    • 2010-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多