Check if Session Has Expired

I've been working on a Phalcon app, I was curious if there was any simple way to check if a session has expired. That way I can notify a user that they've logged out and need to re-login or what have you.



83.4k

When session expire, values in session are reset, you can just check if a variable set in the login is not set anymore:

public function beforeExecuteRoute($dispatcher)
{
    if (!$this->session->has('auth')) {
        $dispatcher->forward(array('controller' => 'index', 'action' => 'index'));
        return false;
    }
}

If, for example:

  • Php stores sessions for 2 hours (php.ini - session maxlifetime)
  • Your app will logout users, if they dont do anything on site for 1 hour

Then, in order to display message like 'You've been logout due inactivity', you will need something like this:

    const NOT_LOGGED_IN = null, MANUAL = 1, INACTIVITY = 2;

    public function logout() {
        $user = $this->session->get('user-secret-info');
        $user->authenticated = false;
        $user->reason = self::MANUAL; // Means, that user logout by himself

        // Dont forget to save session
        $this->sesssion->set('user-secret-info', $user);
    }

    pubcic function isLoggedIn() {
        $user = $this->session->get('user-secret-info');
        if ($user->authenticated == true) {
            if ($user->expired < time() && $user->reason == self::NOT_LOGGED_IN) {

                // Logout user due inactivity
                $user->authenticated = false;
                $user->reason = self::INACTIVITY;

            } else {

                // Slide
                $user->expireTime = time() + $user->expireDelta;

            }
        }

        // Dont forget to save session
        $this->sesssion->set('user-secret-info', $user);
    }