Home > Backend Development > PHP Tutorial > PHP writes file type session to memcache

PHP writes file type session to memcache

WBOY
Release: 2016-08-08 09:26:08
Original
930 people have browsed it
<?php    
    class MemSession{
        private static $handler = null;
        private static $lifetime = null;
        private static $time = null;
        const MS = &#39;session&#39;;
        
        private static function init($handler){
            self::$handler = $handler;
            self::$lifetime = ini_get(&#39;session.gc_maxlifetime&#39;);
            self::$time = time();
        }
        
        public static function start($memcache){
            self::init($memcache);
            //调用类中的方法要用数组,__CLASS__代表本类
            session_set_save_handler(
                array(__CLASS__,&#39;open&#39;),
                array(__CLASS__,&#39;close&#39;),
                array(__CLASS__,&#39;read&#39;),
                array(__CLASS__,&#39;write&#39;),
                array(__CLASS__,&#39;destroy&#39;),
                array(__CLASS__,&#39;gc&#39;)
            );
            session_start();
        }
        
        public static function open($path,$name){
            
        }
        public static function close(){
            
        }
        
        public static function read($PHPSESSID){
            $val = self::$handler->get(self::session_key($PHPSESSID));
            
            if($val===false || $val==null){
                return false;
            }
            return $val;
        }
        public static function write($PHPSESSID,$data){
            $method = $data? 'set':'replace';
            return self::$handler->$method(self::session_key($PHPSESSID),$data,MEMCACHE_COMPRESSED,self::$lifetime);
        }
        
        public static function destroy($PHPSESSID){
            return self::$handle->delete(self::session_key($PHPSESSID));
        }
        //memcache本身就有限定时间,数据自动销毁,所以可不使用gc方法
        public static function gc($lifetime){
            return true;
        }
        
        //给sessionID加前缀,避免key重复
        private static function session_key($PHPSESSID){
            $session_key = self::MS.$PHPSESSID;
            return $session_key;
        }        
    }
    $mem = new Memcache;
    $mem->connect("localhost",11211) or die("could not connect");
    MemSession::start($mem);
Copy after login

The above introduces how PHP writes file type sessions to memcache, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template