当前位置:Gxlcms > PHP教程 > 将Session写下Memcache

将Session写下Memcache

时间:2021-07-01 10:21:17 帮助过:6人阅读

将Session写入Memcache

通过session_set_save_handler()方法自定义Session写入Memcache

 1 php     2     class MemSession{ 3         private static $handler = null; 4         private static $lifetime = null; 5         private static $time = null; 6         const MS = 'session'; 7          8         private static function init($handler){ 9             self::$handler = $handler;10             self::$lifetime = ini_get('session.gc_maxlifetime');11             self::$time = time();12         }13         14         public static function start($memcache){15             self::init($memcache);16             //调用类中的方法要用数组,__CLASS__代表本类17             session_set_save_handler(18                 array(__CLASS__,'open'),19                 array(__CLASS__,'close'),20                 array(__CLASS__,'read'),21                 array(__CLASS__,'write'),22                 array(__CLASS__,'destroy'),23                 array(__CLASS__,'gc')24             );25             session_start();26         }27         28         public static function open($path,$name){29             30         }31         public static function close(){32             33         }34         35         public static function read($PHPSESSID){36             $val = self::$handler->get(self::session_key($PHPSESSID));37             38             if($val===false || $val==null){39                 return false;40             }41             return $val;42         }43         public static function write($PHPSESSID,$data){44             $method = $data? 'set':'replace';45             return self::$handler->$method(self::session_key($PHPSESSID),$data,MEMCACHE_COMPRESSED,self::$lifetime);46         }47         48         public static function destroy($PHPSESSID){49             return self::$handle->delete(self::session_key($PHPSESSID));50         }51         //memcache本身就有限定时间,数据自动销毁,所以可不使用gc方法52         public static function gc($lifetime){53             return true;54         }55         56         //给sessionID加前缀,避免key重复57         private static function session_key($PHPSESSID){58             $session_key = self::MS.$PHPSESSID;59             return $session_key;60         }        61     }62     $mem = new Memcache;63     $mem->connect("localhost",11211) or die("could not connect");64     MemSession::start($mem);

人气教程排行