dtziv24262 2018-03-15 09: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 09: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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?