Check if user logged in on ajax page change

心不动则不痛 提交于 2019-12-04 15:11:11

You should return false so you can do something intelligent, like redirect the user to a log in page, or change the header as you mention in your question, instead of killing the script with die('false')

i.e.

if(!isset($_SESSION['valid_user'])) { 

    return false;
}

or better yet, return a json object to your script and use jquery/javascript to change the header.

$response = array();

if(!isset($_SESSION['valid_user'])) { 

    $response['logged_in'] = false;

} else {

    $response['logged_in'] = true;

}

// return to jquery for handling
return json_encode($response);

either way, you say you're building a web application, so you might want to try handling the event instead of killing the program.

Create a php page that checks the session and returns true or false.

So if the user is not logged in, whenever you do an ajax request and the session doesn't have the user information, only the string false is returned which you can use to check in the ajax callback to display the right information

E.G

if(!isset($_SESSION['user'])) die('false');

Then in your ajax callback, you can check if the response is false, or handle the data another way E.G

$.ajax({"url" : url, "success" : function(response){
    if(response == 'false')
    {
        // display a login screen or redirect the user to a login page
        // E.G showLogin() or document.location = '/login.php';
    } else {
        // to something else with the response if the user is logged in
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!