---
title: "[原创]实现基于Memcache存储的Session类"
author: "varsoft"
date: "2006-12-24T01:35:00Z"
tags: []
slug: "memcache-session"
draft: false
lastmod: "2006-12-24T01:35:00Z"
id: 873787
url: "https://varsoft.iteye.com/blog/873787"
---

**实现基于Memcache存储的Session类**

作者：heiyeluren  
博客：[http://blog.csdn.net/heiyeshuwu](http://blog.csdn.net/heiyeshuwu)

我没事的时候写的自主实现Session功能的类，基于文件方式存储Session数据，测试基本通过，还比较好玩，实际应用没有意义，只不过是学习Session是如何实现的。

使用基于文件的Session存取瓶颈可能都是在磁盘IO操作上，所以对付小数据量的Session没有问题，但是如果碰到大数据量的Sesstion，那么可能无法胜任，现在利用Memcache来保存Session数据，直接通过内存的方式，效率自然能够提高不少，并且如果结合PHP的Memcache扩展，能够支持分布式的Memcache服务器，那么这个性能就能够提到更高，负载更多更复杂的应用。

说明：以下代码基于Memcache来保存Session数据，客户端必须安装有PHP的Memcache扩展，否则无法运行，同时本代码没有经过严格测试，只是作为学习代码。

&lt;?php  
//===========================================  
//程序：Memcache-BasedSessionClass  
//功能：基于Memcache存储的Session功能类  
//作者:heiyeluren  
//博客:http://blog.csdn.net/heiyeshuwu  
//时间:2006-12-23  
//===========================================

/\**  
\*类名:FileSessionClass  
\*功能:自主实现基于Memcache存储的Session功能  
\*描述:这个类就是实现Session的功能,基本上是通过设置客户端的Cookie来保存SessionID,  
\*然后把用户的数据保存在服务器端,最后通过Cookie中的SessionId来确定一个数据是否是用户的,  
\*然后进行相应的数据操作,目前的缺点是没有垃圾收集功能  
\*  
\*本方式适合Memcache内存方式存储Session数据的方式，同时如果构建分布式的Memcache服务器，  
\*能够保存相当多缓存数据，并且适合用户量比较多并发比较大的情况  
\*注意:本类必须要求PHP安装了Memcache扩展,获取Memcache扩展请访问:http://pecl.php.net  
\*/  
classMemcacheSession  
{  
var$sessId='';  
var$sessKeyPrefix='sess\_';  
var$sessExpireTime=86400;  
var$cookieName='\_\_SessHandler';  
var$cookieExpireTime='';  
var$memConfig=array('host'=&gt;'192.168.0.200','port'=&gt;11211);  
var$memObject=null;

/\**  
\*构造函数  
\*  
\*@parambool$isInit-是否实例化对象的时候启动Session  
\*/  
functionMemcacheSession($isInit=false){  
if($isInit){  
$this-&gt;start();  
}  
}

//-------------------------  
//外部方法  
//-------------------------

/\**  
\*启动Session操作  
\*  
\*@paramint$expireTime-Session失效时间,缺省是0,当浏览器关闭的时候失效,该值单位是秒  
\*/  
functionstart($expireTime=0){  
$sessId=$\_COOKIE\[$this-&gt;cookieName];  
if(!$sessId){  
$this-&gt;sessId=$this-&gt;\_getId();  
$this-&gt;cookieExpireTime=($expireTime&gt;0)?time()+$expireTime:0;  
setcookie($this-&gt;cookieName,$this-&gt;sessId,$this-&gt;cookieExpireTime,"/",'');  
$this-&gt;\_initMemcacheObj();  
$\_SESSION=array();  
$this-&gt;\_saveSession();  
}else{  
$this-&gt;sessId=$sessId;  
$\_SESSION=$this-&gt;\_getSession($sessId);  
}  
}

/\**  
\*判断某个Session变量是否注册  
\*  
\*@paramstring$varName-  
\*@returnbool存在返回true,不存在返回false  
\*/  
functionis\_registered($varName){  
if(!isset($\_SESSION\[$varName])){  
returnfalse;  
}  
returntrue;  
}

/\**  
\*注册一个Session变量  
\*  
\*@paramstring$varName-需要注册成Session的变量名  
\*@parammixed$varValue-注册成Session变量的值  
\*@returnbool-该变量名已经存在返回false,注册成功返回true  
\*/  
functionregister($varName,$varValue){  
if(isset($\_SESSION\[$varName])){  
returnfalse;  
}  
$\_SESSION\[$varName]=$varValue;  
$this-&gt;\_saveSession();  
returntrue;  
}

/\**  
\*销毁一个已注册的Session变量  
\*  
\*@paramstring$varName-需要销毁的Session变量名  
\*@returnbool销毁成功返回true  
\*/  
functionunregister($varName){  
unset($\_SESSION\[$varName]);  
$this-&gt;\_saveSession();  
returntrue;  
}

/\**  
\*销毁所有已经注册的Session变量  
\*  
\*@return销毁成功返回true  
\*/  
functiondestroy(){  
$\_SESSION=array();  
$this-&gt;\_saveSession();  
returntrue;  
}

/\**  
\*获取一个已注册的Session变量值  
\*  
\*@paramstring$varName-Session变量的名称  
\*@returnmixed-不存在的变量返回false,存在变量返回变量值  
\*/  
functionget($varName){  
if(!isset($\_SESSION\[$varName])){  
returnfalse;  
}  
return$\_SESSION\[$varName];  
}

/\**  
\*获取所有Session变量  
\*  
\*@returnarray-返回所有已注册的Session变量值  
\*/  
functiongetAll(){  
return$\_SESSION;  
}

/\**  
\*获取当前的SessionID  
\*  
\*@returnstring获取的SessionID  
\*/  
functiongetSid(){  
return$this-&gt;sessId;  
}

/\**  
\*获取Memcache的配置信息  
\*  
\*@returnarrayMemcache配置数组信息  
\*/  
functiongetMemConfig(){  
return$this-&gt;memConfig;  
}

/\**  
\*设置Memcache的配置信息  
\*  
\*@paramstring$host-Memcache服务器的IP  
\*@paramint$port-Memcache服务器的端口  
\*/  
functionsetMemConfig($host,$port){  
$this-&gt;memConfig=array('host'=&gt;$host,'port'=&gt;$port);  
}

//-------------------------  
//内部接口  
//-------------------------

/\**  
\*生成一个SessionID  
\*  
\*@returnstring返回一个32位的SessionID  
\*/  
function\_getId(){  
returnmd5(uniqid(microtime()));  
}

/\**  
\*获取一个保存在Memcache的SessionKey  
\*  
\*@paramstring$sessId-是否指定SessionID  
\*@returnstring获取到的SessionKey  
\*/  
function\_getSessKey($sessId=''){  
$sessKey=($sessId=='')?$this-&gt;sessKeyPrefix.$this-&gt;sessId:$this-&gt;sessKeyPrefix.$sessId;  
return$sessKey;  
}  
/\**  
\*检查保存Session数据的路径是否存在  
\*  
\*@returnbool成功返回true  
\*/  
function\_initMemcacheObj(){  
if(!class\_exists('Memcache')||!function\_exists('memcache\_connect')){  
$this-&gt;\_showMessage('Failed:Memcacheextensionnotinstall,pleasefromhttp://pecl.php.netdownloadandinstall');  
}  
if($this-&gt;memObject&&is\_object($this-&gt;memObject)){  
returntrue;  
}  
$mem=newMemcache;  
if(!@$mem-&gt;connect($this-&gt;memConfig\['host'],$this-&gt;memConfig\['port'])){  
$this-&gt;\_showMessage('Failed:Connectmemcachehost'.$this-&gt;memConfig\['host'].':'.$this-&gt;memConfig\['port'].'failed');  
}  
$this-&gt;memObject=$mem;  
returntrue;  
}

/\**  
\*获取Session文件中的数据  
\*  
\*@paramstring$sessId-需要获取Session数据的SessionId  
\*@returnunknown  
\*/  
function\_getSession($sessId=''){  
$this-&gt;\_initMemcacheObj();  
$sessKey=$this-&gt;\_getSessKey($sessId);  
$sessData=$this-&gt;memObject-&gt;get($sessKey);  
if(!is\_array($sessData)||empty($sessData)){  
$this-&gt;\_showMessage('Failed:SessionID'.$sessKey.'sessiondatanotexists');  
}  
return$sessData;  
}

/\**  
\*把当前的Session数据保存到Memcache  
\*  
\*@paramstring$sessId-SessionID  
\*@return成功返回true  
\*/  
function\_saveSession($sessId=''){  
$this-&gt;\_initMemcacheObj();  
$sessKey=$this-&gt;\_getSessKey($sessId);  
if(empty($\_SESSION)){  
$ret=@$this-&gt;memObject-&gt;set($sessKey,$\_SESSION,false,$this-&gt;sessExpireTime);  
}else{  
$ret=@$this-&gt;memObject-&gt;replace($sessKey,$\_SESSION,false,$this-&gt;sessExpireTime);  
}  
if(!$ret){  
$this-&gt;\_showMessage('Failed:Savesessiontdatafailed,pleasecheckmemcacheserver');  
}  
returntrue;  
}

/\**  
\*显示提示信息  
\*  
\*@paramstring$strMessage-需要显示的信息内容  
\*@parambool$isFailed-是否是失败信息,缺省是true  
\*/  
function\_showMessage($strMessage,$isFailed=true){  
if($isFailed){  
exit($strMessage);  
}  
echo$strMessage;  
}  
}  
?&gt;