Speed up development with full-stack environments for every branch.

Learn More

Using SessionHandler [PHP]

198 Runs 2146 Views 415 Copies


gtsolutions 373

published 4 years ago

 *  PHP Session - Using SessionHandler
 *  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. 

class EncryptedSessionHandler extends SessionHandler
    private $key;

    public function __construct($key)
        $this->key = $key;

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

        return mycrypt_decrypt(MCRYPT_3DES, $this->key, $data, MCRYPT_MODE_ECB);

    public function write($id, $data)
        $data = mcrypt_encrypt(MCRYPT_3DES, $this->key, $data, MCRYPT_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($handler, true);

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

$_SESSION['myvar'] = 'random value';


Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).