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

代码如下:

<?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>";
?>

(0)

相关推荐

  • mysql创建内存表的方法

    如何创建内存表?创建内存表非常的简单,只需注明 ENGINE= MEMORY 即可: 复制代码 代码如下: CREATE TABLE  `tablename` ( `columnName` varchar(256) NOT NUL) ENGINE=MEMORY DEFAULT CHARSET=latin1 MAX_ROWS=100000000; 注意: 当内存表中的数据大于max_heap_table_size设定的容量大小时,mysql会转换超出的数据存储到磁盘上,因此这是性能就大打折扣了,所

  • MySQL内存表的特性与使用介绍

    内存表,就是放在内存中的表,所使用内存的大小可通过My.cnf中的max_heap_table_size指定,如max_heap_table_size=1024M,内存表与临时表并不相同,临时表也是存放在内存中,临时表最大所需内存需要通过tmp_table_size = 128M设定.当数据超过临时表的最大值设定时,自动转为磁盘表,此时因需要进行IO操作,性能会大大下降,而内存表不会,内存表满后,会提示数据满错误. 临时表和内存表都可以人工创建,但临时表更多的作用是系统自己创建后,组织数据以提升

  • MySQL的内存表的基础学习教程

    内存表,就是放在内存中的表,所使用内存的大小可通过My.cnf中的max_heap_table_size指定,如max_heap_table_size=1024M,内存表与临时表并不相同,临时表也是存放在内存中,临时表最大所需内存需要通过tmp_table_size = 128M设定.当数据超过临时表的最大值设定时,自动转为磁盘表,此时因需要进行IO操作,性能会大大下降,而内存表不会,内存表满后,会提示数据满错误. 临时表和内存表都可以人工创建,但临时表更多的作用是系统自己创建后,组织数据以提升

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

    复制代码 代码如下: <?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"); } c

  • MySQL 内存表和临时表的用法详解

    内存表: session 1 $ mysql -uroot root@(none) 10:05:06>use test Database changed root@test 10:06:06>CREATE TABLE tmp_memory (i INT) ENGINE = MEMORY; Query OK, 0 rows affected (0.00 sec) root@test 10:08:46>insert into tmp_memory values (1); Query OK,

  • MySQL内存及虚拟内存优化设置参数

    mysql 优化调试命令   1.mysqld --verbose --help 这个命令生成所有mysqld选项和可配置变量的列表 2.通过连接它并执行这个命令,可以看到实际上使用的变量的值: mysql> SHOW VARIABLES; 还可以通过下面的语句看到运行服务器的统计和状态指标: mysql>SHOW STATUS: 使用mysqladmin还可以获得系统变量和状态信息: shell> mysqladmin variables shell> mysqladmin ex

  • Mysql建表与索引使用规范详解

    一. MySQL建表,字段需设置为非空,需设置字段默认值.二. MySQL建表,字段需NULL时,需设置字段默认值,默认值不为NULL.三. MySQL建表,如果字段等价于外键,应在该字段加索引.四. MySQL建表,不同表之间的相同属性值的字段,列类型,类型长度,是否非空,是否默认值,需保持一致,否则无法正确使用索引进行关联对比.五. MySQL使用时,一条SQL语句只能使用一个表的一个索引.所有的字段类型都可以索引,多列索引的属性最多15个.六. 如果可以在多个索引中进行选择,MySQL通常

  • MySQL删除表的时候忽略外键约束的简单实现

    删除表不是特别常用,特别是对于存在外键关联的表,删除更得小心.但是在开发过程中,发现Schema设计的有问题而且要删除现有的数据库中所有的表来重新创建也是常有的事情:另外在测试的时候,也有需要重新创建数据库的所有表.当然很多自动化工具也可以做这样的事情. 删除表的时候有时会遇到这样的错误消息: ERROR 1217 (23000): Cannot delete or update a parent row: a foreign key constraint fails 这是因为你尝试删除的表中的

  • python3.6连接MySQL和表的创建与删除实例代码

    python3.6不支持importMySQLdb改用为importpymysql模块,需要自行安装模块pymysql. 1:python3.6安装模块pymysql 命令行安装pipinstallpymysql 2:python3.6连接mysql数据库 #!/bin/env Python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect( user="root", password="root@123

  • 为什么说MySQL单表数据不要超过500万行

    今天,探讨一个有趣的话题:MySQL 单表数据达到多少时才需要考虑分库分表?有人说 2000 万行,也有人说 500 万行.那么,你觉得这个数值多少才合适呢? 曾经在中国互联网技术圈广为流传着这么一个说法:MySQL 单表数据量大于 2000 万行,性能会明显下降.事实上,这个传闻据说最早起源于百度.具体情况大概是这样的,当年的 DBA 测试 MySQL性能时发现,当单表的量在 2000 万行量级的时候,SQL 操作的性能急剧下降,因此,结论由此而来.然后又据说百度的工程师流动到业界的其它公司,

随机推荐