phpajaxsessionpushstatepopstate

Check if user logged in on ajax page change


As part of a webapp I'm building I'll need to check if the user is logged in whenever they change page. On a normal non-ajax site this is easy because I can just place the PHP session conditional statement in the header, and the header being called on every page change will determine whether the login page is displayed or not, but seeing as the header file is only set once within an ajax application, which is on the initial load, how can I check whenever the user makes an ajax page request whether or not the session is still valid? Since I'm using pushState and popState I know I can set the condition to run whenever the URL is changed, but I don't know exactly how to code the check to run whenever this happens.

Any and all help appreciated.

Thanks.


Solution

  • 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.