『葉狂人』的怕失憶筆記 Back-End

讓 PHP 的 Session 與 node.js 共用,使用 Memcached

讓 PHP 的 Session 與 node.js 共用

原文網址:PHP and Node.JS session share using memcache

/**
 * http://simplapi.wordpress.com/2012/04/11/php-nodejs-session-share-memcache/
 * memcacheSessionHandler class
 * @class     memcacheSessionHandler
 * @file      memcacheSessionHandler.class.php
 * @brief     This class is used to store session data with memcache, it store in json the session to be used more easily in Node.JS
 * @version     0.1
 * @date      2012-04-11
 * @author      Deisss
 * @licence     LGPLv3
 * This class is used to store session data with memcache, it store in json the session to be used more easily in Node.JS
 */
$version = explode('.', PHP_VERSION);
if (intval($version[0] * 10 + $version[1]) < 54) {
    class memcacheSessionHandler {
        private $host = "goalsoft-memcached";
        private $port = 11211;
        private $lifetime = 0;
        private $memcache = null;

        /**
         * Constructor
         */
        public function __construct(){
            $this->memcache = new Memcached;
            $this->memcache->setOption(Memcached::OPT_COMPRESSION, false); // 不行對資料進行壓縮,不然 node.js 讀不到
            $this->memcache->addServer($this->host, $this->port) or die("Error : Memcache is not ready");
            session_set_save_handler(
                array($this, "open"),
                array($this, "close"),
                array($this, "read"),
                array($this, "write"),
                array($this, "destroy"),
                array($this, "gc")
            );
        }

        /**
         * Destructor
         */
        public function __destruct(){
            session_write_close();
            //$this->memcache->close();
        }

        /**
         * Open the session handler, set the lifetime ot session.gc_maxlifetime
         * @return boolean True if everything succeed
         */
        public function open(){
            $this->lifetime = ini_get('session.gc_maxlifetime');
            return true;
        }

        /**
         * Read the id
         * @param string $id The SESSID to search for
         * @return string The session saved previously
         */
        public function read($id){
            $tmp = $_SESSION;
            $_SESSION = json_decode($this->memcache->get("sessions/{$id}"), true);
            if(isset($_SESSION) && !empty($_SESSION) && $_SESSION != null){
                $new_data = session_encode();
                $_SESSION = $tmp;
                return $new_data;
            }else{
                return "";
            }
        }

        /**
         * Write the session data, convert to json before storing
         * @param string $id The SESSID to save
         * @param string $data The data to store, already serialized by PHP
         * @return boolean True if memcached was able to write the session data
         */
        public function write($id, $data){
            $tmp = $_SESSION;
            session_decode($data);
            $new_data = $_SESSION;
            $_SESSION = $tmp;
            return $this->memcache->set("sessions/{$id}", json_encode($new_data), $this->lifetime);
        }

        /**
         * Delete object in session
         * @param string $id The SESSID to delete
         * @return boolean True if memcached was able delete session data
         */
        public function destroy($id){
            return $this->memcache->delete("sessions/{$id}");
        }

        /**
         * Close gc
         * @return boolean Always true
         */
        public function gc(){
            return true;
        }

        /**
         * Close session
         * @return boolean Always true
         */
        public function close(){
            return true;
        }
    }
} else {
    class memcacheSessionHandler implements SessionHandlerInterface {
        private $host = "goalsoft-memcached";
        private $port = 11211;
        private $lifetime = 0;
        private $memcache = null;
    
        /**
         * Constructor
         */
        public function __construct() {
            $this->memcache = new Memcached;
            $this->memcache->setOption(Memcached::OPT_COMPRESSION, false); // 不行對資料進行壓縮,不然 node.js 讀不到
            $this->memcache->addServer($this->host, $this->port) or die("Error : Memcache is not ready");
            session_set_save_handler($this, true);
        }
    
        /**
         * Destructor
         */
        public function __destruct(){
            session_write_close();
            //$this->memcache->close();
        }
    
        /**
         * Open the session handler, set the lifetime ot session.gc_maxlifetime
         * @return boolean True if everything succeed
         */
        public function open($savePath, $sessionName) {
            $this->lifetime = ini_get('session.gc_maxlifetime');
            return true;
        }
    
        /**
         * Close session
         * @return boolean Always true
         */
        public function close() {
            return true;
        }
    
        /**
         * Read the id
         * @param string $id The SESSID to search for
         * @return string The session saved previously
         */
        public function read($id){
            $tmp = $_SESSION;
            $_SESSION = json_decode($this->memcache->get("sessions/{$id}"), true);
            if(isset($_SESSION) && !empty($_SESSION) && $_SESSION != null){
                $new_data = session_encode();
                $_SESSION = $tmp;
                return $new_data;
            }else{
                return "";
            }
        }
    
        /**
         * Write the session data, convert to json before storing
         * @param string $id The SESSID to save
         * @param string $data The data to store, already serialized by PHP
         * @return boolean True if memcached was able to write the session data
         */
        public function write($id, $data){
            $tmp = $_SESSION;
            session_decode($data);
            $new_data = $_SESSION;
            $_SESSION = $tmp;
            return $this->memcache->set("sessions/{$id}", json_encode($new_data), $this->lifetime);
        }
    
        /**
         * Delete object in session
         * @param string $id The SESSID to delete
         * @return boolean True if memcached was able delete session data
         */
        public function destroy($id){
            return $this->memcache->delete("sessions/{$id}");
        }
    
        /**
         * Close gc
         * @return boolean Always true
         */
        public function gc($maxlifetime){
            return true;
        }
    }
}
『葉狂人』的怕失憶筆記, author
「我不只打破學過的所有規則,還打破我根本不知道的規則。」
奧斯卡最佳導演 馬丁史柯西斯