msession_unlock
Introduction
Session Extensions
PHP Manual

# Session Handling

Table of Contents

- Introduction
- Installing/Configuring
  - Requirements
  - Installation
  - Runtime Configuration
  - Resource Types
- Predefined Constants
- Examples
  - Basic usage
  - Passing the Session ID
  - Custom Session Handlers
- Session Upload Progress
- Sessions and security
- Session Functions
  - session_cache_expire — Return current cache expire
  - session_cache_limiter — Get and/or set the current cache limiter
  - session_commit — Alias of session_write_close
  - session_decode — Decodes session data from a session encoded string
  - session_destroy — Destroys all data registered to a session
  - session_encode — Encodes the current session data as a session encoded string
  - session_get_cookie_params — Get the session cookie parameters
  - session_id — Get and/or set the current session id
  - session_is_registered — Find out whether a global variable is registered in a session
  - session_module_name — Get and/or set the current session module
  - session_name — Get and/or set the current session name
  - session_regenerate_id — Update the current session id with a newly generated one
  - session_register_shutdown — Session shutdown function
  - session_register — Register one or more global variables with the current session
  - session_save_path — Get and/or set the current session save path
  - session_set_cookie_params — Set the session cookie parameters
  - session_set_save_handler — Sets user-level session storage functions
  - session_start — Start new or resume existing session
  - session_status — Returns the current session status
  - session_unregister — Unregister a global variable from the current session
  - session_unset — Free all session variables
  - session_write_close — Write session data and end session
- SessionHandler — The SessionHandler class
  - SessionHandler::close — Close the session
  - SessionHandler::destroy — Destroy a session
  - SessionHandler::gc — Cleanup old sessions
  - SessionHandler::open — Initialize session
  - SessionHandler::read — Read session data
  - SessionHandler::write — Write session data
- SessionHandlerInterface — The SessionHandlerInterface class
  - SessionHandlerInterface::close — Close the session
  - SessionHandlerInterface::destroy — Destroy a session
  - SessionHandlerInterface::gc — Cleanup old sessions
  - SessionHandlerInterface::open — Initialize session
  - SessionHandlerInterface::read — Read session data
  - SessionHandlerInterface::write — Write session data

# 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 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);
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->savePath, 0777);
}
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($handler, true);
session_start();
// proceed to set and retrieve values by key from $_SESSION`