I have been reading several articles and tutorials about the PHP Authentication using Session Management. I have come up with the following code by taking bits and bytes from these tutorials to adapt to my need. Basically I would like the code to do the following tasks:

1. If the user opens the webpage (may be or may not be secured) for the first time, and if he is a registered user and opted for autologin, it should automatically sign in for him. Elseif he did not opted for a autologin, it should direct him to login page and redirect to the restricted page he wanted to see before.
2. If he is not a registered user, it should still create a session.

It would be fairly simple, if all my pages are either secure or not secure. But they I was planning to develop is a simple social networking concept. If the user opens page friends.php without any userid in the url, then it should prompt for the login, but if there is a userid in the url, the user need not login but would be able to see the content.

Please look at the following code to make more sense and I would appreciate it if you could advise me if the code works as what I intended for.


PHP Code:
<?php

class Session {
  
    var 
$db;    // to hold the instance of db class
    
var $hashKey 'secret'// hashKey to encrypt for authorization
    
var $md5 true// to see if the password in the db is encrypted
    
var $session// to hold the instanace of session class
    
var $server// to hold the server variables
    
var $post// to hold the post variables
    
var $cookie// to hold the cookie variables
       
var $expire 0// expire the auth
    
var $expired false// to check the auth expired if the auth didnot opt for autologin
    
var $idle 0// auth idle time in seconds, used incase if the auth didnot opt autologin
    
var $idled false// to hold the auth idled or not
    
var $id 0// the current user's id
       
    
function Session (& $db) {
        
$this->db=& $db;
            
        
        
// Start the session suppress error if already started
        
if (!isset($_SESSION['id']) ) {
            @
session_start();
            
$this->setSessionDefaults();
            
// Assign Some globals to internal references, this will replace _importGlobalVariable
            
$this->session =& $_SESSION;
            
$this->server =& $_SERVER;
            
$this->post =& $_POST;
            
$this->cookie =& $_COOKIE;
            
            if(!
$_SESSION['id']) {
                die(
'Session could not be started by Auth, '
                        
.'possibly headers are already sent, try putting '
                        
.'ob_start in the beginning of your script'); // Throw error                
            
}
  
            if(isset(
$_COOKIE['autoLogin'])){
                
$this->checkRemembered($_COOKIE['autoLogin']);
            }
        }
        else {
            
$this->updateSession();
        }
    }
    
    function 
checkRemembered($cookie) {
        list(
$userLogin$cookie) = @unserialize($cookie);
        
        if (!
$userLogin or !$cookie) return;

        
$userLogin $this->db->quoteSmart($userLogin);
        
$cookie $this->db->quoteSmart($cookie);

        
$sql "SELECT * FROM users WHERE " .
            
"(userLogin = $userLogin) AND (cookie = $cookie)";

        
$result $this->db->getRow($sql);

        if (
is_object($result)) {
            
$this->setAuthSession($resulttrue);
        }
    }
    
    function 
setAuthSession(&$values$remember$init true) {
        
$this->id $values->id;
        
$_SESSION['uid'] = $this->id;
        
$_SESSION['userlogin'] = htmlspecialchars($values->username);
        
$_SESSION['cookie'] = $values->cookie;
        
$_SESSION['logged'] = true;
        
$_SESSION['registered'] = $values->registered;
        
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
        
        if (!
$init) {
            
$_SESSION['last_logged'] = $values->last_logged;
        }
        
        
$_SESSION['style'] = unserialize($values->style);
        if (!isset(
$_SESSION['style']['date'])) {
            
$_SESSION['style']['date'] = 'j M Y';
            
$_SESSION['style']['datetime'] = 'j M Y g:ia';
        }

        if (!
is_null($values->tz)) {
            
$_SESSION['offset'] = $values->tz;
            
set_timezone($values->tz);
        } elseif (isset(
$_SESSION['offset'])) {
            
$this->setTZ($_SESSION['offset']);
        }

        
$_SESSION['name'] = htmlspecialchars($values->name);
        
$_SESSION['email'] = htmlspecialchars($values->email);

        if (
$remember) {
            
$_SESSION['remember'] = true;
            
$this->updateCookie($values->cookietrue);
        }

        
$session $this->db->quote(session_id());
        
$ip $this->db->quote($_SERVER['REMOTE_ADDR']);
        
$sqlinit = ($init) ? ", session = $session, ip = $ip'';

        
$sql "UPDATE users SET last_logged = CURRENT_DATE $sqlinit WHERE id = $this->id";
        
$this->db->query($sql);
    }
    
    function 
setTZ($offset) {
        
$sql "UPDATE member SET tz = $offset WHERE id = $this->id";
        
$this->db->query($sql);
    }
        
    function 
generateCookie() {
        
$cookie mt_rand(1mt_getrandmax());
        
$cookie md5(uniqid($cookie));
        return 
$cookie;
    }


    function 
updateCookie($cookie$force false) {
        
$_SESSION['cookie'] = $cookie;
        if (
$_SESSION['remember'] or $force) {
            
$cookie serialize(array($_SESSION['userLogin'], $cookie));
            
$this->send_cookie('autoLogin'$cookie);
            
            
$sql "UPDATE users SET cookie = $cookie WHERE id = $this->id";
            
$this->db->query($sql);
            
            
        }
    }
        
    function 
send_cookie($name$value) {
        if (!
headers_sent()) {
            
// expires in one year
            
setcookie($name$valuetime() + 31104000'/');
        }
    }
    
    function 
delete_cookie($name) {
        if (!
headers_sent() ) {
            
setcookie($name'bogus'time() - 3600'/');
        }
    }

    function 
updateSession(){
        
$this->session['last_active'] = time();
    }
    
    
    function 
setSessionDefaults() {
    
$_SESSION['logged'] = false;
    
$_SESSION['uid'] = '99999';
    
$_SESSION['userLogin'] = '';
    
$_SESSION['name'] = '';
    
$_SESSION['email'] = '';
    
$_SESSION['cookie'] = 0;
    
$_SESSION['remember'] = false;
    
$_SESSION['registered'] = '0000-00-00';
    
$_SESSION['last_logged'] = null;
    
$_SESSION['login_hash'] = '';
    
$_SESSION['login_error'] = '';
    
$_SESSION['session_start'] = time();
    
$_SESSION['last_active'] = time();
    }
    
/**
    * Checks username and password against database
    * @return void
    * @access private
    */
    
function doLogin($username$password$remember) {   
        
        
$username=quoteSmarty($username);
        
        if ( 
$this->md5 )
            
$password=quoteSmart(md5($username));
        else
            
$password=quoteSmart($password);
        
        
$sql "SELECT * FROM member WHERE " .
            
"(username = $username) AND " .
            
"(password = $password) AND " ;

        
$result $this->db->getRow($sql);

        if (
is_object($result)) {
            
$this->setAuthSession($result$remember);
            return 
true;
        } else {
            
$_SESSION['login_error'] = 'Password and UserName are incorrect';
            
$this->doLogout();
            
$this->redirect(LOGIN_ABSPATH);
            return 
false;
        }
    }  
 
    
/**
    * Confirms that an existing login is still valid
    * @return void
    * @access private
    */
    
function checkLogin() {
        
        if(
$this->session['logged'] == true) {
            
            if(isset(
$_SESSION['remember']) && $_SESSION['remember'] == false) {
            
                
// Check if authentication session is expired
                
if (    isset($this->session)   
                    && 
$this->expire 0
                    
&& isset($this->session['timestamp'])
                    && (
$this->session['timestamp'] + $this->expire) < time()) {
                    
$this->expired true;
                    
$this->doLogout();
                    
$this->session['login_error'] = 'Your session has expired. Please login to proceed.';
                    
$this->redirect(LOGIN_ABSPATH);
                    return 
false;
                }
            
                
// Check if maximum idle time is reached
                
if (    isset($this->session)
                       && 
$this->idle 0
                    
&& isset($this->session['idle']) 
                    && (
$this->session['idle'] + $this->idle) < time()) {
                        
                    
$this->idled true;
                    
$this->dologout();
                    
$this->session['system_error'] = 'Your session has expired due to inactivity. Please login to proceed.';
                    
$this->redirect(LOGIN_ABSPATH);
                    return 
false;
                   }
            }
            
            elseif(isset(
$this->server['HTTP_USER_AGENT']) 
                  && 
$this->session['sessionuseragent'] != $this->server['HTTP_USER_AGENT']) {
                  
$this->expired true;                    
                  
$this->doLogout();
                  
$this->session['login_error'] = 'Your session has to be terminated due to the change in User Agent. Please login to proceed.';;
                  
$this->redirect('LOGIN_ABSPATH');
                  return 
false;
            }
            
            else{
              
                  
$login=$this->session->get('username');
                
$password=$this->session->get('password');
                
$hashKey=$this->session->get('login_hash');
                
                if (   isset(
$this->session['registered']) 
                    && isset(
$this->session['username']) 
                    && 
$this->session['registered'] == true 
                    
&& $this->session['username'] != ''
                    
&& md5($this->hashKey.$login.$password) == $hashKey) {
                    
$this->updateIdle();
                    return 
true;
                }
            }
            
        return 
true;
        }
                
        else {
            
$this->doLogout();
            
$_SESSION['login_error'] = 'You must be logged in.';
            
$this->redirect(LOGIN_ABSPATH);
            return 
false;
        }
    }

    
/**
     * Update the idletime
     *
     * @access private
     * @return void
     */
    
function updateIdle()
    {
        
$this->session['last_active'] = time();
    }   
    
    
/**
    * Logs the user out
    * @param boolean Parameter to pass on to Auth::redirect() (optional)
    * @return void
    * @access public
    */
    
function doLogout () {
        
$this->destroy();
        
$this->refresh();        
    }
    
    function 
uri_self() {
        return 
$_SERVER['PHP_SELF'];
    }
    
    function 
referrer() {
        return 
$_SERVER['REQUEST_URI'];
    }
    
    function 
redirect($url) {
        
header("Location: $url");
        exit();
    }
    
    function 
refresh() {
        
header'Location: '.__FILE__);
        exit();        
    }
    
    
/**
    * Sets a session variable
    * @param string name of variable
    * @param mixed value of variable
    * @return void
    * @access public
    */
    
function set ($name,$value) {
        
$_SESSION[$name]=$value;
    }
    
/**
    * Fetches a session variable
    * @param string name of variable
    * @return mixed value of session varaible
    * @access public
    */
    
function get ($name) {
        if ( isset ( 
$_SESSION[$name] ) )
            return 
$_SESSION[$name];
        else
            return 
false;
    }
    
/**
    * Deletes a session variable
    * @param string name of variable
    * @return boolean
    * @access public
    */
    
function del ($name) {
        if ( isset ( 
$_SESSION[$name] ) ) {
            unset ( 
$_SESSION[$name] );
            return 
true;
        } else {
            return 
false;
        }
    }
    
/**
    * Destroys the whole session
    * @return void
    * @access public
    */
    
function destroy () {
        
$_SESSION = array();
        
session_destroy();
    }
}

?>

I am planning to include this file in a common.php file which will be included in all the files as default and want to call the instance of this class from common.php itself.

Taking friends.php example, if there is userid in the url, I will show the content, but if there is not userid either in the url or in the session, then I will call the class method $session->checkLogin, which will verify if the session is logged in or redirect the user to login page and once authenticated it should redirect him back to friends.php.

I would appreciate it if you could advise me particularly about the checkLogin method. Thanks in advance.