PHP中解决ajax请求session过时退出登陆问题

PHP判断一个请求是Ajax请求仍是普通请求


一、session过时,若是直接是url请求,或者用户在打开的系统页面中直接清除缓存及cookie信息,可直接在php的入口文件中调用如下封装的方法,进行session信息判断以及页面的跳转,如: php

if(empty($_SESSION['sessionid']) || empty($_COOKIE['PHPSESSID'])){

    echo "<script>";
    echo "alert('用户过时,请从新登录!');";
    echo "parent.window.parent.window.location.href = '/index.php';";
    echo "</script>";

}


二、若是是页面保持着,可是10分钟以内没有作任何操做,页不知道是否过时,点击操做按钮,例如保存等,ajax请求已经进行,将会把页面的html打印出来,不能正常的弹出提示窗口,跳转到登录页。 html

项目中进行ajax请求的操做不少,ajax的操做已经进行不能中断,不可能在每一个ajax请求中都调用咱们封装好的判断session是否过时的逻辑,将增长工做负担。我考虑在php的入口代码中调用已经封装好的session过时判断,其返回标识如 echo "timeout";exit; jquery

在引用的jquery.js库中找到.ajax中调用的done方法,补充一下逻辑判断,解决了ajax请求SESSION过时页面跳转问题。 ajax

if(response == "timeout"){
       alert('SESSION信息已过时,请从新登录!');
       parent.window.parent.window.location.href = '/index.php';
       return;
}

php封装的判断session是否过时的方法: 缓存

function checkSession(){

    if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){          
        //is ajax
        if(empty($_SESSION['sessionid'])){
            echo "timeout";
            exit;
        }
    }
    elseif(empty($_SESSION['sessionid']) || empty($_COOKIE['PHPSESSID'])){
        echo "<script>";
        echo "alert('用户过时,请从新登录!');";
        echo "parent.window.parent.window.location.href = '/index.php';";
        echo "</script>";
    }

}
相关文章
相关标签/搜索