dtziv24262 2018-03-15 17:52
浏览 41
已采纳

JS Event Listener无限地检查PHP会话

I want my page to consistently check if the user session is still active. if using event listener. My concern is that php file execution time is limited. is there way to set php execution to infinite? or is there a better way of doing this?

JS:

$(document).ready(function() {
    var loginSource = new EventSource("/structure/ajax/check_login_session.php");

    loginSource.addEventListener("login-verification", function(e) {
        var response = JSON.parse(e.data);
        if (data.login_failed) {
            login_fail_redirect();
        }
    });
})

php

function send_response() {

    if (empty($_SESSION['user_info']) || empty($_SESSION['user_info']['active'])) {

        $response = array("status" => "failed", "login_failed" => 1);

    } else {

        $response = array("status" => "success", "login_failed" => 0);

    }

    echo "event: login-verification
";
    echo 'data: '.json_encode($response);
    echo "

";
    flush();

}
while (true) {
    send_response();
    sleep(2);
}
  • 写回答

1条回答 默认 最新

  • doutan3040 2018-03-15 17:57
    关注

    Use a javascript setInterval instead. It will send timed requests to the backend to check if the session is active or not.

    $(document).ready(function() {
        setInterval(function {
            var loginSource = new EventSource("/structure/ajax/check_login_session.php");
    
            loginSource.addEventListener("login-verification", function(e) {
                var response = JSON.parse(e.data);
                if (data.login_failed) {
                    login_fail_redirect();
                }
            });
        },1000); //time in ms
    })
    

    Then replace this code from your backend:

    while (true) {
        send_response();
        sleep(2);
    }
    

    to

    send_response();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么