<?php class MemSession{ private static $handler = null; private static $lifetime = null; private static $time = null; const MS = 'session'; private static function init($handler){ self::$handler = $handler; self::$lifetime = ini_get('session.gc_maxlifetime'); self::$time = time(); } public static function start($memcache){ self::init($memcache); //调用类中的方法要用数组,__CLASS__代表本类 session_set_save_handler( array(__CLASS__,'open'), array(__CLASS__,'close'), array(__CLASS__,'read'), array(__CLASS__,'write'), array(__CLASS__,'destroy'), array(__CLASS__,'gc') ); 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);
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.