PHP Session Class and $_SESSION Array
- by Gianluca Bargelli
Hello,
i've implemented this custom PHP Session Class for storing sessions into a MySQL database:
class Session
{
    private $_session;
    public $maxTime;
    private $database;
    public function __construct(mysqli $database)
    {
        $this->database=$database;
        $this->maxTime['access'] = time();
        $this->maxTime['gc'] = get_cfg_var('session.gc_maxlifetime');
        session_set_save_handler(array($this,'_open'),
                array($this,'_close'),
                array($this,'_read'),
                array($this,'_write'),
                array($this,'_destroy'),
                array($this,'_clean')
                );
        register_shutdown_function('session_write_close');
        session_start();//SESSION START
    }
    public function _open()
    {
        return true;
    }
    public function _close()
    {
        $this->_clean($this->maxTime['gc']);
    }
    public function _read($id)
    {
        $getData= $this->database->prepare("SELECT data FROM 
                                            Sessions AS Session
                                            WHERE Session.id = ?");
        $getData->bind_param('s',$id);
        $getData->execute();
        $allData= $getData->fetch();
        $totalData = count($allData);
        $hasData=(bool) $totalData >=1;
        return $hasData ? $allData['data'] : '';
    }
    public function _write($id, $data)
    {
        $getData = $this->database->prepare("REPLACE INTO
            Sessions
            VALUES (?, ?, ?)");
        $getData->bind_param('sss', $id, $this->maxTime['access'], $data);
        return $getData->execute();
    }
    public function _destroy($id)
    {
        $getData=$this->database->prepare("DELETE FROM
            Sessions
            WHERE id = ?");
        $getData->bind_param('S', $id);
        return $getData->execute();
    }
    public function _clean($max)
    {
        $old=($this->maxTime['access'] - $max);
        $getData = $this->database->prepare("DELETE FROM Sessions WHERE access < ?");
        $getData->bind_param('s', $old);
        return $getData->execute();
    }
}
It works well but i don't really know how to properly access the $_SESSION array:
For example:  
$db=new DBClass();//This is a custom database class
$session=new Session($db->getConnection());
if (isset($_SESSION['user']))
{
    echo($_SESSION['user']);//THIS IS NEVER EXECUTED!
}
else
{
    $_SESSION['user']="test";
    Echo("Session created!");
}
At every page refresh it seems that $_SESSION['user'] is somehow "resetted", what methods can i apply to prevent such behaviour?