欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

修改Session存放方式为MySQL的类

程序员文章站 2024-02-18 10:07:10
...

lt;?php/*** 修改session存放方式为Mysql Aboc QQ:9986584*/class Session{//过期时间private $_LEFT_TIME = 1440;public funct

/**
* 修改session存放方式为Mysql Aboc QQ:9986584
*/

class Session{

//过期时间
private $_LEFT_TIME = 1440;

public function open() {


}

public function close(){

}

/**
* 读
*/
public function read( $sessid ) {
$sql = "select data from dm_session where sessid ='$sessid' and expiry > time()";
$row = DMmysql::open()->fetchRow( $sql );
return $row['data'];
}

/**
* 写
*/
public function write( $sessid , $sessdata ) {
$data = array(
'expiry' => time()+ $this->_LEFT_TIME,
'data' => $sessdata,
'ip' => '192.168.1.123'
);
if( DMmysql::open()->fetchRow("select sessid from dm_session where sessid ='$sessid'") ) {
//更新
$where = "sessid = '$sessid'";
if( DMmysql::open()->update( 'dm_session',$data,$where ) ){
return true;
} else {
return false;
}
} else {
//插入
$data['sessid'] = $sessid;
if( DMmysql::open()->insert('dm_session',$data) ){
return true;
} else {
return false;
}
}
}

/**
* 指定销毁
*/
public function destroy( $sessid ) {
$where = "sessid = '$sessid'";
if(DMmysql::open()->delete('dm_session',$where)) {
return true;
} else {
return false;
}
}

/**
* 销毁过期的数据
*/
public function gc( $maxlifetime ) {
//随机销毁数据,减轻服务器压力
if( rand(0,3) == 3 ) {
$where = "expiry if( DMmysql::open()->delete('dm_session',$where) ) {
return true;
} else {
return false;
}
}
}

}

$session = new Session();
session_set_save_handler(
array(&$session,'open'),
array(&$session,'close'),
array(&$session,'read'),
array(&$session,'write'),
array(&$session,'destroy'),
array(&$session,'gc')
);
session_start();
?>


在每个使用session的文件前include一下就行了

数据库:

CREATE TABLE `dm_session` (
`sessid` char(32) NOT NULL default '',
`expiry` int(10) NOT NULL default '0',
`data` text NOT NULL,
`ip` char(15) NOT NULL default '',
PRIMARY KEY (`sessid`),
KEY `sesskid` (`sessid`,`expiry`)
) ENGINE=MyISAM DEFAULT CHARSET=gbk;

修改Session存放方式为MySQL的类