session_set_save_handler

(PHP 4, PHP 5, PHP 7, PHP 8)

session_set_save_handlerSets user-level session storage functions

Description

session_set_save_handler(
    callable $open,
    callable $close,
    callable $read,
    callable $write,
    callable $destroy,
    callable $gc,
    callable $create_sid = ?,
    callable $validate_sid = ?,
    callable $update_timestamp = ?
): bool

It is possible to register the following prototype:

session_set_save_handler(object $sessionhandler, bool $register_shutdown = true): bool

session_set_save_handler() sets the user-level session storage functions which are used for storing and retrieving data associated with a session. This is most useful when a storage method other than those supplied by PHP sessions is preferred, e.g. storing the session data in a local database.

Parameters

This function has two prototypes.

sessionhandler

An instance of a class implementing SessionHandlerInterface, and optionally SessionIdInterface and/or SessionUpdateTimestampHandlerInterface, such as SessionHandler, to register as the session handler.

register_shutdown

Register session_write_close() as a register_shutdown_function() function.

or
open

A callable with the following signature:

open(string $savePath, string $sessionName): bool

The open callback works like a constructor in classes and is executed when the session is being opened. It is the first callback function executed when the session is started automatically or manually with session_start(). Return value is true for success, false for failure.

close

A callable with the following signature:

close(): bool

The close callback works like a destructor in classes and is executed after the session write callback has been called. It is also invoked when session_write_close() is called. Return value should be true for success, false for failure.

read

A callable with the following signature:

read(string $sessionId): string

The read callback must always return a session encoded (serialized) string, or an empty string if there is no data to read.

This callback is called internally by PHP when the session starts or when session_start() is called. Before this callback is invoked PHP will invoke the open callback.

The value this callback returns must be in exactly the same serialized format that was originally passed for storage to the write callback. The value returned will be unserialized automatically by PHP and used to populate the $_SESSION superglobal. While the data looks similar to serialize() please note it is a different format which is specified in the session.serialize_handler ini setting.

write

A callable with the following signature:

write(string $sessionId, string $data): bool

The write callback is called when the session needs to be saved and closed. This callback receives the current session ID a serialized version the $_SESSION superglobal. The serialization method used internally by PHP is specified in the session.serialize_handler ini setting.

The serialized session data passed to this callback should be stored against the passed session ID. When retrieving this data, the read callback must return the exact value that was originally passed to the write callback.

This callback is invoked when PHP shuts down or explicitly when session_write_close() is called. Note that after executing this function PHP will internally execute the close callback.

Note:

The "write" handler is not executed until after the output stream is closed. Thus, output from debugging statements in the "write" handler will never be seen in the browser. If debugging output is necessary, it is suggested that the debug output be written to a file instead.

destroy

A callable with the following signature:

destroy(string $sessionId): bool

This callback is executed when a session is destroyed with session_destroy() or with session_regenerate_id() with the destroy parameter set to true. Return value should be true for success, false for failure.

gc

A callable with the following signature:

gc(int $lifetime): bool

The garbage collector callback is invoked internally by PHP periodically in order to purge old session data. The frequency is controlled by session.gc_probability and session.gc_divisor. The value of lifetime which is passed to this callback can be set in session.gc_maxlifetime. Return value should be true for success, false for failure.

create_sid

A callable with the following signature:

create_sid(): string

This callback is executed when a new session ID is required. No parameters are provided, and the return value should be a string that is a valid session ID for your handler.

validate_sid

A callable with the following signature:

validate_sid(string $key): bool

This callback is executed when a session is to be started, a session ID is supplied and session.use_strict_mode is enabled. The key is the session ID to validate. A session ID is valid, if a session with that ID already exists. The return value should be true for success, false for failure.

update_timestamp

A callable with the following signature:

update_timestamp(string $key, string $val): bool

This callback is executed when a session is updated. key is the session ID, val is the session data. The return value should be true for success, false for failure.

Return Values

Returns true on success or false on failure.

Examples

Example #1 Custom session handler: see full code in SessionHandlerInterface synopsis.

We just show the invocation here, the full example can be seen in the SessionHandlerInterface synopsis linked above.

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
{
// implement interfaces here
}

$handler = new MySessionHandler();
session_set_save_handler($handler, true);
session_start();

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

Notes

Warning

The write and close handlers are called after object destruction and therefore cannot use objects or throw exceptions. Exceptions are not able to be caught since will not be caught nor will any exception trace be displayed and the execution will just cease unexpectedly. The object destructors can however use sessions.

It is possible to call session_write_close() from the destructor to solve this chicken and egg problem but the most reliable way is to register the shutdown function as described above.

Warning

Current working directory is changed with some SAPIs if session is closed in the script termination. It is possible to close the session earlier with session_write_close().

See Also

add a note

User Contributed Notes 39 notes

up
47
andreipa at gmail dot com
10 years ago
After spend so many time to understand how PHP session works with database and unsuccessful attempts to get it right, I decided to rewrite the version from our friend stalker.

//Database
CREATE TABLE `Session` (
  `Session_Id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `Session_Expires` datetime NOT NULL,
  `Session_Data` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`Session_Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
SELECT * FROM mydatabase.Session;

<?php
//inc.session.php

class SysSession implements SessionHandlerInterface
{
    private $link;
    
    public function open($savePath, $sessionName)
    {
        $link = mysqli_connect("server","user","pwd","mydatabase");
        if($link){
            $this->link = $link;
            return true;
        }else{
            return false;
        }
    }
    public function close()
    {
        mysqli_close($this->link);
        return true;
    }
    public function read($id)
    {
        $result = mysqli_query($this->link,"SELECT Session_Data FROM Session WHERE Session_Id = '".$id."' AND Session_Expires > '".date('Y-m-d H:i:s')."'");
        if($row = mysqli_fetch_assoc($result)){
            return $row['Session_Data'];
        }else{
            return "";
        }
    }
    public function write($id, $data)
    {
        $DateTime = date('Y-m-d H:i:s');
        $NewDateTime = date('Y-m-d H:i:s',strtotime($DateTime.' + 1 hour'));
        $result = mysqli_query($this->link,"REPLACE INTO Session SET Session_Id = '".$id."', Session_Expires = '".$NewDateTime."', Session_Data = '".$data."'");
        if($result){
            return true;
        }else{
            return false;
        }
    }
    public function destroy($id)
    {
        $result = mysqli_query($this->link,"DELETE FROM Session WHERE Session_Id ='".$id."'");
        if($result){
            return true;
        }else{
            return false;
        }
    }
    public function gc($maxlifetime)
    {
        $result = mysqli_query($this->link,"DELETE FROM Session WHERE ((UNIX_TIMESTAMP(Session_Expires) + ".$maxlifetime.") < ".$maxlifetime.")");
        if($result){
            return true;
        }else{
            return false;
        }
    }
}
$handler = new SysSession();
session_set_save_handler($handler, true);
?>

<?php
//page 1
require_once('inc.session.php');

session_start();

$_SESSION['var1'] = "My Portuguese text: SOU Gaucho!";
?>

<?php
//page 2
require_once('inc.session.php');

session_start();

if(isset($_SESSION['var1']){
echo $_SESSION['var1']; 
}
//OUTPUT: My Portuguese text: SOU Gaucho!
?>
up
13
ohcc at 163 dot com
8 years ago
As of PHP 7.0, you can implement SessionUpdateTimestampHandlerInterface to 
define your own session id validating method like validate_sid and the timestamp updating method like update_timestamp in the non-OOP prototype of session_set_save_handler().

SessionUpdateTimestampHandlerInterface is a new interface introduced in PHP 7.0, which has not been documented yet. It has two abstract methods: SessionUpdateTimestampHandlerInterface :: validateId($sessionId) and SessionUpdateTimestampHandlerInterface :: updateTimestamp($sessionId, $sessionData).

<?php
    /*
       @author Wu Xiancheng
       Code structure for PHP 7.0+ only because SessionUpdateTimestampHandlerInterface is introduced in PHP 7.0
       With this class you can validate php session id and update the timestamp of php session data
       with the OOP prototype of session_set_save_handler() in PHP 7.0+
    */
    class PHPSessionXHandler implements SessionHandlerInterface, SessionUpdateTimestampHandlerInterface {
        public function close(){
            // return value should be true for success or false for failure
            // ...
        }
        public function destroy($sessionId){
            // return value should be true for success or false for failure
            // ... 
        }
        public function gc($maximumLifetime){
            // return value should be true for success or false for failure
            // ...
        }
        public function open($sessionSavePath, $sessionName){
            // return value should be true for success or false for failure
            // ...
        }
        public function read($sessionId){
            // return value should be the session data or an empty string
            // ...
        }
        public function write($sessionId, $sessionData){
            // return value should be true for success or false for failure
            // ...
        }
        public function create_sid(){
            // available since PHP 5.5.1
            // invoked internally when a new session id is needed
            // no parameter is needed and return value should be the new session id created
            // ...
        }
        public function validateId($sessionId){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true if the session id is valid otherwise false
            // if false is returned a new session id will be generated by php internally
            // ...
        }
        public function updateTimestamp($sessionId, $sessionData){
            // implements SessionUpdateTimestampHandlerInterface::validateId()
            // available since PHP 7.0
            // return value should be true for success or false for failure
            // ...
        }
    }
?>
up
4
polygon dot co dot in at gmail dot com
4 years ago
Below is a demo to check the order in which session function executes.

<?php

ini_set('session.use_strict_mode',true);

function sess_open($sess_path, $sess_name) {
    echo '<br/>sess_open';
    return true;
}

function sess_close() {
    echo '<br/>sess_close';
    return true;
}

function sess_read($sess_id) {
    echo '<br/>sess_read';
    return '';
}

function sess_write($sess_id, $data) {
    echo '<br/>sess_write';
    return true;
}

function sess_destroy($sess_id) {
    echo '<br/>sess_destroy';
    return true;
}

function sess_gc($sess_maxlifetime) {
    echo '<br/>sess_gc';
    return true;
}

function sess_create_sid() {
    echo '<br/>sess_create_sid';
    return 'RNS'.rand(0,10);
}

function sess_validate_sid($sess_id) {
    echo '<br/>sess_validate_sid';
    return true;
}

function sess_update_timestamp($sess_id,$data) {
    echo '<br/>sess_update_timestamp';
    return true;
}

session_set_save_handler(
    'sess_open',
    'sess_close',
    'sess_read',
    'sess_write',
    'sess_destroy',
    'sess_gc',
    'sess_create_sid',
    'sess_validate_sid',
    'sess_update_timestamp'
);

session_start();

echo '<br/>code here...';

?>

O/P Below when above code executed first time.
sess_open
sess_create_sid
sess_read
code here...
sess_write
sess_close

O/P Below for next execution.
sess_open
sess_validate_sid
sess_read
code here...
sess_write
sess_close
up
4
ohcc at 163 dot com
8 years ago
What is not documented is that callables $validate_sid and $update_timestamp are supported since PHP 7.0. for the 
 prototype of "bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] )".

validate_sid($sessionId)
  This callback is to validate $sessionId. Its return value should be true for valid session id $sessionId or false for invalid session id $sessionId. If false is returned, a new session id is generated to replace the invalid session id $sessionId.

update_timestamp($sessionId)
  This call back is to update timestamp, and its return value should be true for success or false for failure.

If you use this prototype, if you provide less than 6 parameters or if you provide more parameters than session_set_save_handler() accepts, you will get a "Wrong parameter count for session_set_save_handler()" warning.

If you use the OOP prototype of session_set_save_handler(SessionHandlerInterface $sessionhandler [, bool $register_shutdown = true ] ), a member method named neither validate_sid nor update_timestamp of the class of $sessionhandler are not invoked even in PHP 7.2, but a member method named create_sid is supported as of PHP 5.5.1.

It's 16th December, 2017 today, the documetation even PHP may get updated sometime afterwards.
up
5
Steven George
11 years ago
Note that as well as destructing objects before calling write() and close(), it seems PHP also destroys classes.  That is, you can't even call a static method of an external class in the write() and close() handlers - PHP will issue a Fatal error stating "Class xxxx not found"
up
3
tomas at slax dot org
17 years ago
Regarding the SAPIs: The warning mentioned in function's description (that the Current working directory is changed with some SAPIs) is very important.

It means that if your callback 'write' function needs to write to a file in current directory, it will not find it. You have to use absolute path and not rely upon the current working directory.

I thought this warning applies only to some strange environments like Windows, but it happens exactly on Linux + Apache 2.2 + PHP 5.
up
3
korvus at kgstudios dot net
20 years ago
It seems when you call 'session_name()', php loads the session id automatically from GET ( if the index exists ) and passes it to the 'read' callback method correctly, but the 'write' callback is invoked twice: first the auto-generated session id, then the custom session id

So be aware of what queries you execute inside the callback .. I got crazy because I used a MySQL 'REPLACE' statement to agilize, and I spent a lot of hours trying to understand why 2 rows instead of 1 were being affected ( the first id was inserting, the second updating )

I hope this helps!
up
2
peter at brandrock dot co dot za
7 years ago
If saving to a database, as in the examples on this page, for performance, consider the following.

Build the Sessions table with an index on the SessionExpires column to quickly identify rows to be deleted in the garbage collection phase.

Rather do a garbage collection "delete from sessions where expiresOn < $now" on every session start/open. If you have an index on expiry time, this will not be a big hit, and evens out the load across all users. If it is possible that a large number of sessions will expire at the same time, include a "limit 100" clause, set for whatever number is reasonable, so that each user shares the load.

Use a varchar rather than Text to store the data, as Text will store the column off-page and is retrieved slightly slower. Use Text only if your application really does store large amounts of text in the session.
up
2
centurianii at yahoo dot co dot uk
8 years ago
Adding to the very useful class from: andreipa at gmail dot com

1. You should handle session expiration & data I/O from the SessionHandlerInterface methods,
2. You should NOT handle session regeneration and data modification from these methods but from a static method, e.g. sth like Session::start().
3. PHP gives a lot of examples but does NOT say what's the perspective under which one should work.

A skeleton of such a class:
namespace xyz;
class Session implements \SessionHandlerInterface, Singleton {
   /** @var SessionToken $token The SessionToken of this command; 
          this is part of my programming approach */
   protected $token;
   /** @var PDO $dbh The PDO handler to the database */
   protected $dbh;
   /** @var $savePath Where sessions are stored */
   protected $savePath;
   /** @var $type Type of sessions (['files'|'sqlite']) */
   protected $type;
   /** @var self $instance An instance of this class */
   static private $instance = null;

   private function __construct() { ... }
   static public function getInstance() {
      if (self::$instance === null) {
         self::$instance = new self();
      }
      return self::$instance;
   }
   public function open($savePath, $sessionName) { ... }
   public function close() {
      if ($this->type == static::FILES) {
         return true;
      } elseif ($this->type == static::SQLITE) {
         return true;
      }
   }
   public function read($id) { ... }
   public function write($id, $data) { ... }
   public function destroy($id) { ... }
   public function gc($maxlifetime) { ... }
   static public function get($key) {
      return (isset($_SESSION[$key]))? $_SESSION[$key] : null;
   }
   static public function set($key, $value) {
      return $_SESSION[$key] = $value;
   }
   static public function newId() {...}
   static public function start($call = null, $log = false) {
      //1. start session (send 1st header)
      if (session_status() != PHP_SESSION_ACTIVE) {
         session_start();   //calls: open()->read()
      }

      //2. $_SESSION['session']: array of session control data
      // existed session
      if (is_array(static::get('session'))) {
         $session = static::get('session');
      // new session
      } else {
         $session = array();
      }

      $tmp = $_SESSION;
      //do sth with $session array...
      static::set('session', $session);
      session_write_close();   //calls: write()->read()->close()
      //create a new session inside if...else...
      session_id(static::newId());
      session_start();   //calls: open()->read()
      //if you want previous session data to be copied:
      //$_SESSION = $tmp;
      //do sth else with $session array and save it to new session...
      static::set('session', $session);

      //6. call callback function (only on valid/new sessions)
      if ($call)
         $call();
      session_write_close();   //calls: write()->read()->close()
   }
   /**
    * Defines custom session handler.
    */
   static public function setHandler() {
      // commit automatic session
      if (ini_get('session.auto_start') == 1) {
         session_write_close();
      }
      $handler = static::getInstance();
      session_set_save_handler($handler, true);
   }
}

Let's start a session:
Session::setHandler();
Session::start();

Trying for hours to trace my error where the 3rd Session::read() ended to use a null Session::dbh until I realized that Session::close() should NOT destroy properties of this class!
Also I avoid the use of session_create_id() as it's only for PHP 7 >= 7.1.0 and I use in place a static Session::newId().
up
2
shanikawm at gmail dot com
9 years ago
Here is a class to handle session using an Oracle table.
https://github.com/shanikawm/PHP_Oracle_Based_Session_Handler_Class

<?php
/**
 * By Shanika Amarasoma
 * Date: 6/24/2016
 * PHP session handler using Oracle database
 * Oracle Create table statement
        CREATE TABLE PHP_SESSIONS
        (
            SESSION_ID  VARCHAR2(256 BYTE) UNIQUE,
            DATA        CLOB,
            TOUCHED     NUMBER(38)
        );
 */
class session_handler implements SessionHandlerInterface
{
    private $con;
    public function __construct() {
        if(!$this->con=oci_pconnect(DBUSER,DBPASS,CONNECTION_STR)){
            die('Database connection failed !');
        }
    }
    public function open($save_path ,$name){
        return true;
    }
    public function close(){
        return true;
    }
    public function read($session_id){
        $query = "SELECT \"DATA\" FROM PHP_SESSIONS WHERE SESSION_ID=Q'{" . $session_id . "}'";
        $stid = oci_parse($this->con, $query);
        oci_execute($stid, OCI_DEFAULT);
        $row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_LOBS);
        oci_free_statement($stid);
        return $row['DATA'];
    }
    public function write($session_id,$session_data){
        $dquery="DELETE FROM PHP_SESSIONS WHERE SESSION_ID=Q'{".$session_id."}'";
        $dstid = oci_parse($this->con,$dquery);
        oci_execute($dstid, OCI_NO_AUTO_COMMIT);
        oci_free_statement($dstid);
        $query="INSERT INTO PHP_SESSIONS(SESSION_ID,TOUCHED,\"DATA\") VALUES(Q'{".$session_id."}',".time().",EMPTY_CLOB()) RETURNING \"DATA\" INTO :clob";
        $stid = oci_parse($this->con,$query);
        $clob=oci_new_descriptor($this->con,OCI_D_LOB);
        oci_bind_by_name($stid, ':clob', $clob, -1, OCI_B_CLOB);
        if(!oci_execute($stid, OCI_NO_AUTO_COMMIT)){
            @oci_free_statement($stid);
            return false;
        }
        if($clob->save($session_data)){
            oci_commit($this->con);
            $return=true;
        } else {