This class is used to manage and store sessions using a MySQL database. The advantages of this are:

  • Your data is more secure than when using the default session files
    • This is especially important if you are on a shared server
  • You are able to use multiple servers that can all access the same session data
  • You can query the database to find the number of active sessions, or to see who is logged in, etc.

To begin, setup the following MySQL Table:

DROP TABLE IF EXISTS `sessions`; 
CREATE TABLE `sessions` ( 
  `id` varchar(32) NOT NULL, 
  `data` text, 
  `last_accessed` timestamp NOT NULL default CURRENT_TIMESTAMP, 
  PRIMARY KEY  (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Other than that, there is nothing to document. Just include the file once and your session has begun. Just like the Database Class, it is critical that this file is only included once. I figure that every time I need to access the database, a session should be created right along with it. So I wrote the following function:

function open_database () { // opens a connection do your database, and starts a session 
  global $mysqli; 
  include_once (BASE . 'common/classes/Database.php'); 
  include_once (BASE . 'common/classes/Session.php'); 
}

So in my script when I've determined that I'm going to be using the database (which is almost always - but not always), I open_database() and off I go.

Download