自定义session处理机制之数据库存储session

自定义session处理机制主要由session_set_save_handler()函数实现。注意参数的顺序

首先在数据库中建立session表

CREATE TABLE `session` (
  `sid` char(32) NOT NULL DEFAULT '',
  `data` varchar(255) NOT NULL DEFAULT '',
  `mtime` int(10) NOT NULL DEFAULT '0',
  `ip` char(15) NOT NULL DEFAULT '',
  `card` char(32) NOT NULL DEFAULT ''    //该项主要存储用户的ip、浏览器信息等,用来判断用户的sessionid是否合法,以防止用户sessionid被劫持后伪造用户登录
) ENGINE=MyISAM DEFAULT CHARSET=gbk

自己写的session处理类

<?php
class session{
	protected $conn;
	protected $card;
	protected $max_time;
	protected $table;
	public function __construct(){
		if(ini_get('session.save_handler')=='user' || ini_set('session.save_handler', 'user')){
			session_set_save_handler(
				array($this,'start'),
				array($this,'close'),
				array($this,'read'),
				array($this,'write'),
				array($this,'destroy'),
				array($this,'gc')
				);
			$this->conn=mysql_connect('localhost','root','root') or die('连接错误!');
			mysql_select_db('test');
			$this->table='session';
			$this->max_time=100;
			$this->card=md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']);
			session_start();
		}
	}
	public function start($path,$sess_name){
		echo "start</br>";
	}
	public function read($sid){
		$sql="select `data` from `".$this->table."` where `sid`='{$sid}' and data='".$this->card."'";
		// echo $sql;
		$result=mysql_query($sql);
		$row=mysql_fetch_assoc($result);
		echo "read</br>";
		return mysql_affected_rows()>0 ? $row['data']:'';
	}
	public function write($sid,$data){
		// $sql="update "
		$sql  = "select `sid` from ".$this->table." where `sid` ='{$sid}' and `card`='".$this->card."'";  
		mysql_query($sql);
		$time=time();
		if(mysql_affected_rows()>0){
			$sql="update `".$this->table."` set `data`='{$data}',`mtime`={$time} where `sid`='{$sid}'";
			echo $sql;
		}else{
			$sql="insert into ".$this->table." (`sid`,`data`,`mtime`,`ip`,`card`) values ('{$sid}','{$data}','{$time}','{$_SERVER['REMOTE_ADDR']}','".$this->card."')";
		}
		echo "write</br>";
		return mysql_query($sql)?true:false;
	}
	public function close(){
		self::gc($this->max_time);
		echo "close</br>";
		mysql_close($this->conn);
		return true;
	}
	public function destroy($sid){
		$sql="delete from ".$this->table." where `sid`='{$sid}'";
		mysql_query($sql);
		return true;
	}
	public function gc($max_time){
		$max_time=$this->max_time;
		$time=time();
		$sql="delete from ".$this->table." where `mtime`<".($time-$max_time);
		mysql_query($sql);
		echo "gc</br>";
		return true;
	}
}
$session=new session();
$_SESSION['username']='zhangsan';
$_SESSION['age']=20;


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值