Storing PHP Sessions in a Database - Overriding the session storage (
Page 3 of 8 )
As I just said, the session_set_save_handler() function will allow us to override the default method of storing data. According to the documentation, here is the format for this function:
bool session_set_save_handler ( callback $open, callback $close, callback $read, callback $write, callback $destroy, callback $gc );
In our example, I'm going to create a session class that can be used to store information to the database instead of to a file.
For starters, create a new file called "sessions.php." Inside this file, put the following code:
class SessionManager {
var $life_time;
function SessionManager() {
// Read the maxlifetime setting from PHP
$this->life_time = get_cfg_var("session.gc_maxlifetime");
// Register this object as the session handler
session_set_save_handler(
array( &$this, "open" ),
array( &$this, "close" ),
array( &$this, "read" ),
array( &$this, "write"),
array( &$this, "destroy"),
array( &$this, "gc" )
);
}
}
In the above example, the SessionManager() class and its constructor are created. You will notice that instead of merely passing function names into the session_set_save_handler() function, I sent arrays allowing me to identify class methods as the intercepts for the session actions.
 |