Session Handling

Table of Contents

The SessionHandler class

Introduction

SessionHandler a special class that can be used to expose the current internal PHP session save handler by inheritance. There are six methods which wrap the six internal session save handler callbacks (open, close, read, write, destroy and gc). By default, this class will wrap whatever internal save handler is set as as defined by the session.save_handler configuration directive which is usually files by default. Other internal session save handlers are provided by PHP extensions such as SQLite (as sqlite), Memcache (as memcache), and Memcached (as memcached).

When a plain instance of SessionHandler is set as the save handler using session_set_save_handler it will wrap the current save handlers. A class extending from SessionHandler allows you to override the methods or intercept or filter them by calls the parent class methods which ultimately wrap the interal PHP session handlers.

This allows you, for example, to intercept the read and write methods to encrypt/decrypt the session data and then pass the result to and from the parent class. Alternatively one might chose to entirely override a method like the garbage collection callback gc.

Because the SessionHandler wraps the current internal save handler methods, the above example of encryption can be applied to any internal save handler without having to know the internals of the handlers.

To use this class, first set the save handler you wish to expose using session.save_handler and then pass an instance of SessionHandler or one extending it to session_set_save_handler.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. The return values are equally processed internally by PHP. For more information on the session workflow, please refer session_set_save_handler.

Class synopsis

SessionHandler
class SessionHandler implements SessionHandlerInterface {
/* Methods */
public bool close ( void )
public bool destroy ( string $session_id )
public bool gc ( int $maxlifetime )
public bool open ( string $save_path , string $session_id )
public string read ( string $session_id )
public bool write ( string $session_id , string $session_data )
}
Warning

This class is designed to expose the current internal PHP session save handler, if you you want to write your own custom save handlers, please implement the SessionHandlerInterface interface instead of extending from SessionHandler.

Example #1 Using SessionHandler to add encryption to internal PHP save handlers.

<?php
class EncryptedSessionHandler extends SessionHandler
{
    private 
$key;

    public function 
__construct($key)
    {
        
$this->key $key;
    }

    public function 
read($id)
    {
        
$data parent::read($id);

        return 
mcrypt_decrypt(MCRYPT_3DES$this->key$dataMCRYPT_MODE_ECB);
    }

    public function 
write($id$data)
    {
        
$data mcrypt_encrypt(MCRYPT_3DES$this->key$dataMCRYPT_MODE_ECB);

        return 
parent::write($id$data);
    }
}

// we'll intercept the native 'files' handler, but will equally work
// with other internal native handlers like 'sqlite', 'memcache' or 'memcached'
// which are provided by PHP extensions.
ini_set('session.save_handler''files');
$handler = new EncryptedSessionHandler('mykey');
session_set_save_handler($handlertrue);
session_start();

// proceed to set and retrieve values by key from $_SESSION

Note:

Since this class' methods are designed to be called internally by PHP as part of the normal session workflow, child class calls to parent methods (i.e. the actual internal native handlers) will return FALSE unless the session has actually been started (either automatically, or by explicit session_start. This is important to consider when writing unit tests where the class methods might be invoked manually.

The SessionHandlerInterface class

Introduction

SessionHandlerInterface is an interface which defines a prototype for creating a custom session handler. In order to pass a custom session handler to session_set_save_handler using its OOP invocation, the class must implement this interface.

Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code.

Class synopsis

SessionHandlerInterface
class SessionHandlerInterface {
/* Methods */
abstract public bool close ( void )
abstract public bool destroy ( string $session_id )
abstract public bool gc ( string $maxlifetime )
abstract public bool open ( string $save_path , string $name )
abstract public string read ( string $session_id )
abstract public bool write ( string $session_id , string $session_data )
}

Example #1 Example using SessionHandlerInterface

The following example provides file based session storage similar to the PHP sessions default save handler files. This example could easily be extended to cover database storage using your favorite PHP supported database engine.

Note we use the OOP prototype with session_set_save_handler and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers.

<?php
class MySessionHandler implements SessionHandlerInterface
{
    private 
$savePath;

    public function 
open($savePath$sessionName)
    {
        
$this->savePath $savePath;
        if (!
is_dir($this->savePath)) {
            
mkdir($this->savePath0777);
        }

        return 
true;
    }

    public function 
close()
    {
        return 
true;
    }

    public function 
read($id)
    {
        return (string)@
file_get_contents("$this->savePath/sess_$id");
    }

    public function 
write($id$data)
    {
        return 
file_put_contents("$this->savePath/sess_$id"$data) === false false true;
    }

    public function 
destroy($id)
    {
        
$file "$this->savePath/sess_$id";
        if (
file_exists($file)) {
            
unlink($file);
        }

        return 
true;
    }

    public function 
gc($maxlifetime)
    {
        foreach (
glob("$this->savePath/sess_*") as $file) {
            if (
filemtime($file) + $maxlifetime time() && file_exists($file)) {
                
unlink($file);
            }
        }

        return 
true;
    }
}

$handler = new MySessionHandler();
session_set_save_handler($handlertrue);
session_start();

// proceed to set and retrieve values by key from $_SESSION