Shabat Closer

Sunday, March 20, 2016

PHP : save session Handler to memcached by class

PHP : save session Handler to memcached by class


use this class to save session to memcache by class


<?php
/**
 * Memcache PHP Session Handler
*/
define("SESSION_MEMCACHED_HOST","127.0.0.1"); //Memcache server address

if(! interface_exists('SessionHandlerInterface'))
{
  interface SessionHandlerInterface {
    public function close();
    public function destroy($session_id);
    public function gc($maxlifetime);
    public function open($save_path, $name);
    public function read($session_id);
    public function write($session_id, $session_data);
  }
}

class Memcached_SessionHandler implements SessionHandlerInterface{
   
  /**
   * @var int
   */
  public $lifeTime;

  /**
   * @var Memcached
   */
  public $memcached;

  /**
   * @var MySQLi
   */
  public $mysqli;

  /**
   * @var string
   */
  public $initSessionData;

  /**
   * interval for session expiration update in the DB
   * @var int
   */
  protected $_refreshTime = 1800; //30 minutes

  private $sessionPrefix="";
  
  

  /**
   * constructor of the handler - initialises Memcached object
   *
   * @return bool
   */
  public function __construct()
  {
 $this->sessionPrefix=".session.";
 
    // this ensures to write down and close the session when destroying the
    // handler object
    ini_set('session.save_handler', 'user');
    register_shutdown_function("session_write_close");

    $this->lifeTime = intval(ini_get("session.gc_maxlifetime"));
    $this->initSessionData = null;

    session_set_save_handler(
        array($this, "open"),
        array($this, "close"),
        array($this, "read"),
        array($this, "write"),
        array($this, "destroy"),
        array($this, "gc"));

    return true;
  } // __construct()






  /**
   * Init memcached connection.
   */
  protected function initMemcached()
  {
  /*
    if($this->memcached instanceOf Memcached)
    {
      return false;
    }
 */
    $this->memcached = new Memcache;
 $this->memcached->addServer(SESSION_MEMCACHED_HOST, 11211);
    return true;
  } // initMemcached()



  /**
   * opening of the session - mandatory arguments won't be needed
   * we'll get the session id and load session data, it the session exists
   *
   * @param string $savePath
   * @param string $sessionName
   * @return bool
   */
  public function open($savePath, $sessionName)
  {
    $this->initMemcached();

    $session_id = session_id();
    if ($session_id !== "") {
      $this->initSessionData = $this->read($session_id);
    }

    return true;
  } // open()



  /**
   * closing the session
   *
   * @return bool
   */
  public function close()
  {
    $this->lifeTime = null;
    $this->initSessionData = null;

    unset($this->memcached);
    return true;
  } // close()



  /**
   * reading of the session data
   * if the data couldn't be found in the Memcache, we try to load it from the
   * DB we have to update the time of data expiration in the db using
   * _updateDbExpiration() the life time in Memcache is updated automatically
   * by write operation
   *
   * @param string $session_id
   * @return string
   */
  public function read($session_id)
  {
    $now = time();
    $data = $this->memcached->get($this->sessionPrefix.$session_id);
    $this->memcached->set($this->sessionPrefix.$session_id, $data,MEMCACHE_COMPRESSED, $this->lifeTime);
    return $data ? $data : '';
  } // read()



  /**
   * cache write - this is called when the script is about to finish,
   * or when session_write_close() is called
   * data are written only when something has changed
   *
   * @param string $session_id
   * @param string $data
   * @return bool
   */
  public function write($session_id, $data){
    // we store time of the db record expiration in the Memcache
    $result = $this->memcached->set($this->sessionPrefix.$session_id, $data, MEMCACHE_COMPRESSED,$this->lifeTime);
 return $result;
  } // write()



  /**
   * destroy of the session
   *
   * @param string $session_id
   * @return bool
   */
  public function destroy($session_id){
    $this->memcached->delete($this->sessionPrefix.$session_id);
    return true;
  } // destroy()



  /**
   * called by the garbage collector
   *
   * @param int $maxlifetime
   * @return bool
   */
  public function gc($maxlifetime){
    return true;
  } // gc()
}


Useage :


<?php
// Initialize custom session management.
new Memcached_SessionHandler();


Enjoy!

No comments:

Post a Comment