把ssession写到Memcache中
1、把session写到Memcache中的类:memsession.class.php
<?php class MemSession { private static $handler=null; private static $lifetime=null; private static $time = null; const NS='session_'; private static function init($handler){ self::$handler=$handler; self::$lifetime=ini_get('session.gc_maxlifetime');
self::$time=time(); } public static function start(Memcache $memcache){ self::init($memcache); 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){ return true; } public static function close(){ return true; } public static function read($PHPSESSID){ $out=self::$handler->get(self::session_key($PHPSESSID)); if($out===false || $out == null) return ''; return $out; } 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::$handler->delete(self::session_key($PHPSESSID)); } public static function gc($lifetime){ return true; } private static function session_key($PHPSESSID){ $session_key=self::NS.$PHPSESSID; return $session_key; } } $memcache=new Memcache; $memcache->connect("localhost", 11211) or die("could not connect!"); MemSession::start($memcache); ?>
2、session值定义页面:one.php
<?php include "session.class.php"; $_SESSION["isLogin3"]=1; $_SESSION["username"]="admin"; $_SESSION["uid"]=333; echo session_name().'='.session_id().'<br>'; ?>
3、从另外页面取值的页面:two.php
<?php include "session.class.php"; print_r($_SESSION); echo '<br>'; echo session_name().'='.session_id().'<br>'; ?>
4、销毁页面:three.php
<?php include "session.class.php"; $_SESSION=array(); if(isset($_COOKIE[session_name()])){ setCookie(session_name(), '', time()-100, '/'); } session_destroy(); echo session_name().'='.session_id().'<br>'; ?>
5、把Memcache中值取出来的:items.php
<?php $mem=new Memcache; $host="localhost"; $port=11211; $mem->connect($host,$port); $items=$mem->getExtendedStats("items"); $items=$items["$host:$port"]['items']; print_r($items); foreach($items as $value){ foreach($value as $item){ $number=$item["number"]; $arr=$mem->getExtendedStats("cachedump",$number,0); print_r($arr); $line=$arr["$host:$port"]; if( is_array($line) && count($line)>0){ foreach($line as $key=>$value){ echo $key.'=>'; print_r($mem->get($key)); echo "<br>"; } } } }