用mysql内存表来代替php session的类


Posted in PHP onFebruary 01, 2009
<?php 
/** 
@Usage: use some other storage method(mysql or memcache) instead of php sessoin 
@author:lein 
@Version:1.0 
*/ 
session_start(); 
if(!isset($_SESSION['test'])){ 
$_SESSION['test']="123_lein_".date("Y-m-d H:i:s"); 
} class session{ 
//session data 
private $data; 
//engine,mysql or memcache 
private $engine; 
//php session expire time 
private $sessionexpiredTime; 
//current user's session cookie value 
private $sessionID; 
public function session($engineBase=NULL,$engineName='mysql',$storage_name='php_session'){ 
try{ 
$this->sessionexpiredTime = intval(ini_get("session.cache_expire"))*60; 
}catch(Exception $Exception){ 
$this->sessionexpiredTime = 1200; 
} 
@session_start(); 
$this->sessionID=session_id(); 
$className = $engineName."SessionEngine"; 
$this->engine = new $className( 
array( 
'storage_name'=>$storage_name,//mysql table name or memcahce key which stores data; 
'expire_time'=>$this->sessionexpiredTime, 
'data_too_long_instead_value' => '{__DATA IS *$* TO LONG__}' 
), 
$this->sessionID, 
&$engineBase 
); 
$this->init(); 
$this->engine->refresh(); 
$this->engine->cleanup(); 
} 
private function init() 
{ 
$this->data = $this->engine->get(); 
if(emptyempty($this->data)&&!emptyempty($_SESSION)){ 
$this->data = $_SESSION; 
$this->engine->create(false, $this->data); 
} 
else if(emptyempty($this->data)) 
{ 
$this->engine->create(false, $this->data); 
} 
} 
private function __get($nm) 
{ 
if (isset($this->data[$nm])) { 
$r = $this->data[$nm]; 
return $r; 
} 
else 
{ 
return NULL; 
} 
} 
private function __set($nm, $val) 
{ 
$this->data[$nm] = $val; 
$this->engine->set(false, $this->data); 
} 
function __destruct(){ 
$this->data = NULL; 
$this->engine->close(); 
$this->engine = NULL; 
} 
} 
interface SessionEngine 
{ 
/* 
* set varibles 
* @param $arr array,array(varible name=>varible value,...) 
*/ 
public function setVariable($arr); 
/* 
* get session value 
* @param $key string 
*/ 
public function get($key=""); 
/* 
* set session value 
* @param $key string 
* @param $value string 
*/ 
public function set($key="",$value=""); 
/* 
* set session value 
* @param $key string 
* @param $value string 
*/ 
public function create($key="",$value=""); 
/* 
* update the session's invalid time 
* @param $key string 
*/ 
public function refresh($key=""); 
/* 
* close mysql or memcache connection 
*/ 
public function close(); 
/* 
* delete expired sessions 
*/ 
public function cleanup(); 
} 
final class mysqlSessionEngine implements SessionEngine{ 
private $id=""; 
private $storage_name='php_session'; 
private $storage_name_slow='php_session_slow'; 
private $data_too_long_instead_value = '{__DATA IS ~ TO LONG__}';//if data is longer than $max_session_data_length and you are using mysql 4 or below,insert this value into memery table instead. 
private $expire_time=1200; 
private $max_session_data_length = 2048; 
private $conn; 
private $mysql_version; 
public function mysqlSessionEngine($arr=array(),$key="",&$_conn){ 
$this->setVariable($arr); 
$this->id = $key; 
if(emptyempty($this->id)||strlen($this->id)!=32){ 
throw new Exception(__FILE__."->".__LINE__.": Session's cookie name can't be empty and it must have just 32 charactors!"); 
} 
$this->conn = $_conn; 
if(!$this->conn||!is_resource($this->conn)){ 
throw new Exception(__FILE__."->".__LINE__.": Need a mysql connection!"); 
} 
$this->mysql_version = $this->getOne("select floor(version())"); 
if($this->mysql_version<5){ 
$this->max_session_data_length = 255; 
} 
} 
public function setVariable($arr){ 
if(!emptyempty($arr)&&is_array($arr)){ 
foreach($arr as $k=>$v){ 
$this->$k = $v; 
if($k=='storage_name'){ 
$this->storage_name_slow = $v.'_slow'; 
} 
} 
} 
} 
public function get($key=""){ 
if($key=="") $key = $this->id; 
$return = $this->getOne('select value from '.$this->storage_name.' where id="'.$key.'"'); 
if($return==$this->data_too_long_instead_value) 
{ 
$return = $this->getOne('select value from '.$this->storage_name_slow.' where id="'.$key.'"'); 
} 
if(!$return) 
{ 
$mysqlError = mysql_error($this->conn); 
if(strpos($mysqlError,"doesn't exist")!==false) 
{ 
$this->initTable(); 
} 
$return = array(); 
} 
else 
{ 
$return = unserialize($return); 
} 
return $return; 
} 
public function close(){ 
@mysql_close($this->conn); 
} 
public function cleanup(){ 
if($this->mysql_version>4){ 
$sql = 'delete from '.$this->storage_name.' while date_add(time,INTERVAL '.$this->expire_time.' SECOND)<CURRENT_TIMESTAMP()'; 
}else{ 
$sql = 'delete from '.$this->storage_name.' while time+'.$this->expire_time.'<unix_timestamp()'; 
} 
$this->execute($sql); 
} 
public function refresh($key=""){ 
if($this->mysql_version>4){ 
$sql = 'update '.$this->storage_name.' set time=CURRENT_TIMESTAMP() where id="'.$key.'"'; 
}else{ 
$sql = 'update '.$this->storage_name.' set time=unix_timestamp() where id="'.$key.'"'; 
} 
$return = $this->execute($sql); 
if(!$return){ 
$this->initTable(); 
$return = $this->execute($sql,true); 
} 
return $return; 
} 
public function create($key="",$value=""){ 
if($key=="") $key = $this->id; 
if($value != "") $value = mysql_real_escape_string(serialize($value),$this->conn); 
if(strlen($value)>$this->max_session_data_length) throw new Exception(__FILE__."->".__LINE__.": Session data is long than max allow length(".$this->max_session_data_length.")!"); 
if($this->mysql_version>4){ 
$sql = 'replace into '.$this->storage_name.' set value=\''.$value.'\',id="'.$key.'",time=CURRENT_TIMESTAMP()'; 
}else{ 
$sql = 'replace into '.$this->storage_name.' set value=\''.$value.'\',id="'.$key.'",time=unix_timestamp()'; 
} 
$return = $this->execute($sql); 
if(!$return){ 
$this->initTable(); 
$return = $this->execute($sql,true); 
} 
return $return; 
} 
public function set($key="",$value=""){ 
if($key=="") $key = $this->id; 
if($value != "") $value = mysql_real_escape_string(serialize($value),$this->conn); 
$sql = 'update '.$this->storage_name.' set value=\''.$value.'\' where id="'.$key.'"'; 
if(strlen($value)>$this->max_session_data_length) 
{ 
if($this->mysql_version>4){ 
throw new Exception(__FILE__."->".__LINE__.": Session data is long than max allow length(".$this->max_session_data_length.")!"); 
} 
$sql = 'replace into '.$this->storage_name_slow.' set value=\''.$value.'\',id="'.$key.'",time=unix_timestamp()'; 
$this->execute($sql,true); 
$sql = 'update '.$this->storage_name.' set value=\''.$this->data_too_long_instead_value.'\' where id="'.$key.'"'; 
} 
$return = $this->execute($sql); 
if(!$return){ 
$this->initTable(); 
$return = $this->execute($sql,true); 
} 
return $return; 
} 
private function initTable(){ 
if($this->mysql_version>4){ 
$sql = " 
CREATE TABLE if not exists `".$this->storage_name."` ( 
`id` char(32) NOT NULL default 'ERR', 
`value` VARBINARY(".$this->max_session_data_length.") NULL, 
`time` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP, 
PRIMARY KEY (`id`), 
KEY `time` (`time`) 
) ENGINE=MEMORY; 
"; 
}else{ 
$sqlSlow = " 
CREATE TABLE if not exists `".$this->storage_name."_slow` ( 
`id` char(32) NOT NULL default 'ERR', 
`value` text NULL, 
`time` int(10) not null default '0', 
PRIMARY KEY (`id`), 
KEY `time` (`time`) 
) ENGINE=MyISAM; 
"; 
$this->execute($sqlSlow,true); 
$sql = " 
CREATE TABLE if not exists `".$this->storage_name."` ( 
`id` char(32) NOT NULL default 'ERR', 
`value` VARCHAR(255) NULL, 
`time` int(10) not null default '0', 
PRIMARY KEY (`id`), 
KEY `time` (`time`) 
) ENGINE=MEMORY; 
"; 
} 
return $this->execute($sql,true); 
} 
private function execute($sql,$die=false) 
{ 
if($die) 
{ 
mysql_query($sql,$this->conn) or die("exe Sql error:<br>".mysql_error()."<br>".$sql."<hr>"); 
} 
else 
{ 
mysql_query($sql,$this->conn); 
if(mysql_error()){ 
return false; 
}else{ 
return true; 
} 
} 
} 
private function getOne($sql,$die=false){ 
$rs = $this->query($sql,$die); 
if($rs && ($one = mysql_fetch_row($rs)) ){ 
return $one[0]; 
}else{ 
return false; 
} 
} 
private function query($sql,$die=false){ 
if($die) 
$rs = mysql_query($sql,$this->conn) or die("query Sql error:<br>".mysql_error()."<br>".$sql."<hr>"); 
else 
$rs = mysql_query($sql,$this->conn); 
return $rs; 
} 
} 
$lnk = mysql_connect('localhost', 'root', '123456') 
or die ('Not connected : ' . mysql_error()); 
// make foo the current db 
mysql_select_db('test', $lnk) or die ('Can\'t use foo : ' . mysql_error()); 
$S = new session($lnk); 
if(!$S->last){ 
$S->last = time(); 
} 
echo "First visit at ".$S->last."<br>"; 
if(!$S->lastv){ 
$S->lastv = 0; 
} 
$S->lastv++; 
echo "lastv=".$S->lastv."<br>"; 
echo "test=".$S->test."<br>"; 
if(isset($_GET['max'])){ 
$S->boom = str_repeat("OK",255); 
} 
if(isset($_GET['boom'])){ 
$S->boom = $_GET['boom']; 
} 
echo "boom=".$S->boom."<br>"; 
?>
PHP 相关文章推荐
杏林同学录(四)
Oct 09 PHP
基于HTTP长连接的&quot;服务器推&quot;技术的php 简易聊天室
Oct 31 PHP
php绝对路径与相对路径之间关系的的分析
Mar 03 PHP
Codeigniter实现多文件上传并创建多个缩略图
Jun 12 PHP
php数组比较实现查找连续数的方法
Jul 29 PHP
PHP中抽象类和抽象方法概念与用法分析
May 24 PHP
php while循环控制的简单实例
May 30 PHP
Yii数据读取与跳转参数传递用法实例分析
Jul 12 PHP
php实现贪吃蛇小游戏
Jul 26 PHP
php 变量引用与变量销毁机制详细介绍
Dec 05 PHP
thinkphp3.2同时连接两个数据库的简单方法
Aug 13 PHP
php ActiveMQ的安装与使用方法图文教程
Feb 23 PHP
PHP 加密/解密函数 dencrypt(动态密文,带压缩功能,支持中文)
Jan 30 #PHP
防止MySQL注入或HTML表单滥用的PHP程序
Jan 21 #PHP
php 动态多文件上传
Jan 18 #PHP
PHP $_SERVER详解
Jan 16 #PHP
php 删除数组元素
Jan 16 #PHP
php完全过滤HTML,JS,CSS等标签
Jan 16 #PHP
php array_flip() 删除数组重复元素
Jan 14 #PHP
You might like
隐藏X-Space个人空间下方版权方法隐藏X-Space个人空间标题隐藏X-Space个人空间管理版权方法
2007/02/22 PHP
解析php curl_setopt 函数的相关应用及介绍
2013/06/17 PHP
PHP以mysqli方式连接类完整代码实例
2014/07/15 PHP
php限制文件下载速度的代码
2015/10/20 PHP
解析页面加载与js函数的执行 onload or ready
2013/12/12 Javascript
js与jquery获取父级元素,子级元素,兄弟元素的实现方法
2014/01/09 Javascript
js函数参数设置默认值的一种变通实现方法
2014/05/26 Javascript
js使用栈来实现10进制转8进制与取除数及余数
2014/06/11 Javascript
Javascript基础教程之数据类型 (数值 Number)
2015/01/18 Javascript
基于jQuery Ajax实现上传文件
2016/03/24 Javascript
Extjs表单输入框异步校验的插件实现方法
2017/03/20 Javascript
Vue之Watcher源码解析(1)
2017/07/19 Javascript
Nodejs异步回调之异常处理实例分析
2018/06/22 NodeJs
JS中appendChild追加子节点无效的解决方法
2018/10/14 Javascript
js实现多个倒计时并行 js拼团倒计时
2019/02/25 Javascript
vue实现微信获取用户信息的方法
2019/03/21 Javascript
微信小程序点击保存图片到本机功能
2019/12/13 Javascript
vue 在methods中调用mounted的实现操作
2020/08/07 Javascript
[44:50]DOTA2上海特级锦标赛B组小组赛#2 VG VS Fnatic第二局
2016/02/26 DOTA
跟老齐学Python之传说中的函数编写条规
2014/10/11 Python
python 实现判断ip连通性的方法总结
2018/04/22 Python
python实现将一个数组逆序输出的方法
2018/06/25 Python
对Python Pexpect 模块的使用说明详解
2019/02/14 Python
Python 图像处理: 生成二维高斯分布蒙版的实例
2019/07/04 Python
Django组件content-type使用方法详解
2019/07/19 Python
基于keras 模型、结构、权重保存的实现
2020/01/24 Python
python模拟点击玩游戏的实例讲解
2020/11/26 Python
html5组织文档结构_动力节点Java学院整理
2017/07/11 HTML / CSS
Canvas与Image互相转换示例代码
2013/08/09 HTML / CSS
高三励志标语
2014/06/05 职场文书
倡导文明标语
2014/06/16 职场文书
会计专业求职信
2014/08/10 职场文书
小学生十佳少年事迹材料
2014/08/20 职场文书
德育标兵事迹材料
2014/08/24 职场文书
2014年置业顾问工作总结
2014/11/17 职场文书
2016年元旦主持词
2015/07/06 职场文书