What is a “pretty and proper OO” way for handling sessions and authentication?

Posted by asdfqwer on Programmers See other posts from Programmers or by asdfqwer
Published on 2011-02-06T04:20:22Z Indexed on 2011/02/06 7:33 UTC
Read the original article Hit count: 473

Filed under:

Is coupling these two concepts a bad approach?

As of right now I'm delegating all session handling and whether or not a user desires to logout in my config.inc file. As I was writing my Auth class I started wondering whether or not my Auth class should be taking care of most of the logic in my config.inc. Regardless, I'm sure there's a more elegant way of handling this...

Here is what I have in my config.inc (also a large chunk of this code is based on a reply I found on SO except I can't find the source ._.):

ini_set('session.name', 'SID');

# session management
session_set_cookie_params(24*60*60); // set SID cookie lifetime
session_start();
if(isset($_SESSION['LOGOUT']) {
    session_destroy(); // destroy session data
    $_SESSION = array(); // destroy session data sanity check
    setcookie('SID', '', time() - 24*60*60); // destroy session cookie data
    #header('Location: '.DOCROOT);
} elseif(isset($_SESSION['SID_AUTH'])) { // verify user has authenticated

    if (!isset($_SESSION['SID_CREATED'])) {
        $_SESSION['SID_CREATED'] = time();
    } elseif (time() - $_SESSION['SID_CREATED'] > 6*60*60) {
        // session started more than 6 hours ago
        session_regenerate_id(); // reset SID value
        $_SESSION['SID_CREATED'] = time();  // update creation time
    }

    if (isset($_SESSION['SID_MODIFIED']) && (time() - $_SESSION['SID_MODIFIED'] > 12*60*60)) {
        // last request was more than 12 hours ago
        session_destroy(); // destroy session data
        $_SESSION = array(); // destroy session data sanity check
        setcookie('SID', '', time() - 24*60*60); // destroy session cookie data
    }

    $_SESSION['SID_MODIFIED'] = time(); // update last activity time stamp
}

© Programmers or respective owner

Related posts about oop