javascript - php非登录情况下session超时如何避免?

标签 javascript php jquery ajax session

我已经为 session 超时设置了 2 分钟,如果它发生了页面 将重定向到 session 超时页面。

但是,我有一些页面可以在不登录的情况下浏览。 在这些页面中,如果我离开它超过 2 分钟,将出现弹出窗口要求用户重新登录。用户将返回单击它,它将重定向到 session 超时页面。

谁能教我,如何摆脱这种情况,使无需登录即可浏览的页面不应该出现在 session 时间?

ajax.js

window.onload = init;
var interval;
function init() {
    interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
    var xmlReq = false;
    try {
        xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xmlReq = false;
        }
    }
    if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
        xmlReq = new XMLHttpRequest();
    }

    xmlReq.open('get', 'check.php', true);
    xmlReq.setRequestHeader("Connection", "close");
    xmlReq.send(null);
    xmlReq.onreadystatechange = function() {
        if (xmlReq.readyState == 4 && xmlReq.status == 200) {
            if (xmlReq.responseText == 1) {
                clearInterval(interval);
                alert('You have been logged out. You will now be redirected to home page.');
                document.location.href = "index.php";
            }
        }
    }
}

第一个 session

<?php
// session_start ();
if (! isset ( $_SESSION ["isLoggedIn"] ) || ! ($_SESSION ['isLoggedIn'])) {
    // code for authentication comes here
    // ASSUME USER IS VALID
    $_SESSION ['isLoggedIn'] = true;

    $_SESSION ['timeOut'] = 120;
    $logged = time ();
    $_SESSION ['loggedAt'] = $logged;
    // showLoggedIn ();
} else {
    require 'timeCheck.php';
    $hasSessionExpired = checkIfTimedOut ();
    if ($hasSessionExpired) {
        session_unset ();
        header ( "Location:index.php" );
        exit ();
    } else {
        $_SESSION ['loggedAt'] = time (); 
    }
}
?>

footer.php

<?php include ('includes/firstSession.php'); ?>
<footer class="main">
<div class="wrapper container">
    <div class="copyright">All Rights Reserved
    </div>

    <div class="logo"><img src="images/logo.png"></div>

</footer>
</div>

ajax.js 草稿

window.onload = init;
var interval;
function init() {
    interval = setInterval(trackLogin, 1000);
}
function trackLogin() {
    var xmlReq = false;
    try {
        xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e2) {
            xmlReq = false;
        }
    }
    if (!xmlReq && typeof XMLHttpRequest != 'undefined') {
        xmlReq = new XMLHttpRequest();
    }

    xmlReq.open('get', 'check.php', true);
    xmlReq.setRequestHeader("Connection", "close");
    xmlReq.send(null);
    xmlReq.onreadystatechange = function() {
        if (xmlReq.readyState == 4 && xmlReq.status == 200) {
            return json_encode(array(
                    'role' => $_SESSION['role'], //assuming something like guest/logged-in
                    'user_id'   => $_SESSION['user_id']
                ));
            var obj = xmlReq.responseText;
            var jsonObj = JSON.parse(obj);
            //now we can make a comparison against our keys 'role' and 'user_id'

            if(jsonObj['role'] == 'guest'){
                //guest role, do something here
            } else if (jsonObj['role'] == 'logged-in') {
                alert('You have been logged out. You will now be redirected to home page.');
                document.location.href = "index.php";
                //do something else for logged in users
            }

最佳答案

我认为,由于无论是否登录,您都有一个持续存在的 session ,因此您需要根据用户名(无论如何设置)执行您的操作。看看这是否是您想要做的。为了清楚起见,我做了注释:

myfunctions.php

<?php
// return a session set on not set OR false if set
function is_loggedin()
    {
        return (!empty($_SESSION["isLoggedIn"]));
    }
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
    {
        return (!empty($_SESSION["username"]));
    }
// Do your set time function
function set_time_out($timeout = 120)
    {
        $_SESSION['isLoggedIn'] =   true;
        $_SESSION['timeOut']    =   (is_numeric($timeout))? $timeout : 120;
        $_SESSION['loggedAt']   =   time();
    }

function process_timeout($supRed = false)
    {
        // If a user has NOT already been poking around your site
        if(!is_loggedin()) {
                // Set the timeout
                set_time_out();
                return 0;
            }
        else {
                // If a navigating user is logged in
                if(user_set())  {
                        // Check for expire time
                        require('timeCheck.php');
                        // If they have been timed out
                        if(checkIfTimedOut()) {
                                if(!$supRed) {
                                        // destroy the session and forward to login (or wherever)
                                        session_destroy();
                                        header("Location:index.php" );
                                        exit();
                                    }

                                return 1;
                            }
                    }
                // Set the logged time by default
                $_SESSION['loggedAt']   =   time(); 
            }

        return 0;
    }

header.php

<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
process_timeout();
?><!DOCTYPE html>
...etc

check.php

<?php
include_once("includes/firstSession.php");
include_once("includes/myfunctions.php");
echo process_timeout(true);

编辑:

这是完整的脚本,包括 js 和 php。

// return a session set on not set OR false if set
function is_loggedin()
    {
        return (!empty($_SESSION["isLoggedIn"]));
    }
// Check if username is set (not sure how your usernames are stored in your session
// but that is what you want to check here
function user_set()
    {
        return (!empty($_SESSION["username"]));
    }
// Do your set time function
function set_time_out($timeout = 120)
    {
        $_SESSION['isLoggedIn'] =   true;
        $_SESSION['timeOut']    =   (is_numeric($timeout))? $timeout : 120;
        $_SESSION['loggedAt']   =   time();
    }

function checkIfTimedOut()
    {
        if(!empty($_SESSION['loggedAt'])) {
                $active =   ($_SESSION['loggedAt'] + strtotime("120 seconds"));
                $now    =   time();
                return (($active - $now) > 0);
            }

        return true;
    }

function process_timeout($supRed = false)
    {
        // If a user has NOT already been poking around your site
        if(!is_loggedin()) {
                // Set the timeout
                set_time_out();
                return 0;
            }
        else {
                // If a navigating user is logged in
                if(user_set())  {
                        // Check for expire time
                        // If they have been timed out
                        if(checkIfTimedOut()) {
                                // destroy the session
                                session_destroy();
                                if(!$supRed) {
                                         // Forward to login (or wherever)
                                        header("Location:index.php" );
                                        exit();
                                    }
                                return 1;
                            }
                    }
                // Set the logged time by default
                $_SESSION['loggedAt']   =   time(); 
            }

        return 0;
    }

check.php:

// Include the functions here
if(!empty($_POST['getPost'])) {
    echo json_encode(array("redirect"=>process_timeout(true),"sess"=>$_SESSION));
    exit;   
}

调用页面:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
function init()
    {
        interval = setInterval(trackLogin, 2000);
    }

function trackLogin()
    {
        $.ajax({
                url: '/check.php',
                data: { getPost: true },
                type: 'post',
                success: function(response) {
                        var instr   =   JSON.parse(response);
                        console.log(response);

                        if(instr.redirect == 1) {
                                clearInterval(interval);
                                alert('You have been logged out. You will now be redirected to home page.');
                                document.location.href = "index.php";
                            }
                    }
        });
    }

$(document).ready(function() {
    var interval;
    init();
});
</script>

EDITED

enter image description here

关于javascript - php非登录情况下session超时如何避免?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33470657/

相关文章:

javascript - 将带有空格的文本从 python 后端传递到 html View

javascript - 无法在 react-redux-form 控件中包装 react-autocomplete 元素

php - 安装 SilverStripe 时出现 RedisException

javascript - PHP 发送器与 js

jquery - 如何在 Accordion 主面板上显示帮助图标

javascript - AngularJS - 使用 jQuery 获取当前元素

javascript - 在固定 div 上滚动时防止正文滚动

javascript - 获取变化范围的值以使其他元素出现

php - AS3 RSAKey.sign() != PHP openssl_sign() 函数

php - static 关键字对常量有影响吗?