session入库
session需要保存的值有三个 会话编号.会话值,过期时间
create table sess(
sess_id varchar(50) primary key comment '会话编号',
sess_value varchar(2000) comment '会话内容',
sess_time int not null comment '会话产生的时间'
)engine=memory charset=utf8 comment '会话表'
创建数据表 :
小建议: 时间可以用datetime 也可以用int 但为什么一般用int?
因为datetime占8字节 int占4字节
保存会话表引擎为什么使用memory?
因为memory引擎将数据存储在内存中 速度极快,重启Mysql服务器数据消失..
代码实现
通过session_set_save_handler 更改会话存储
06.png<?php
$link=mysqli_connect('localhost','root','root','php15');
mysqli_set_charset($link,'utf8');
function open() { //开启会话
return true;
}
function close() { //关闭会话
return true;
}
function read($sess_id) { //读取会话
global $link;
$sql="select sess_value from sess where sess_id='$sess_id'";
$rs=mysqli_query($link,$sql);
if($rows=mysqli_fetch_row($rs))
return $rows[0];
return '';
}
function write($sess_id,$sess_value) { //写入会话
global $link;
$time=time();
$sql="insert into sess values ('$sess_id','$sess_value',$time) on duplicate key update sess_value='$sess_value',sess_time=$time";
return mysqli_query($link,$sql);
}
function destroy($sess_id) { //销毁会话
global $link;
$sql="delete from sess where sess_id='$sess_id'";
return mysqli_query($link,$sql);
}
//$lifetime int PHP的会话生命周期
function gc($lifetime) { //垃圾回收
global $link;
$time=time()-$lifetime; //垃圾时间的临界点
$sql="delete from sess where sess_time<$time";
return mysqli_query($link,$sql);
}
session_set_save_handler('open','close','read','write','destroy','gc');
session_start();
$_SESSION['name']='tom';
//session_destroy();
在类中实现继承接口
<?php
$link=mysqli_connect('198.168.38.99','sess','sess','session');
mysqli_set_charset($link,'utf8');
interface SessionHandlerInterface{
function open();
function close();
function read();
function write();
function destroy();
function gc();
}
class MySessionHandler extends SessionHandlerInterface{
public function open() { //开启会话
return true;
}
public function close() { //关闭会话
return true;
}
public function read($sess_id) { //读取会话
global $link;
$sql="select sess_value from sess where sess_id='$sess_id'";
$rs=mysqli_query($link,$sql);
if($rows=mysqli_fetch_row($rs))
return $rows[0];
return '';
}
public function write($sess_id,$sess_value) { //写入会话
global $link;
$time=time();
$sql="insert into sess values ('$sess_id','$sess_value',$time) on duplicate key update sess_data='$sess_value',sess_time=$time";
return mysqli_query($link,$sql);
}
public function destroy($sess_id) { //销毁会话
global $link;
$sql="delete from sess where sess_id='$sess_id'";
return mysqli_query($link,$sql);
}
//$lifetime int PHP的会话生命周期
public function gc($lifetime) { //垃圾回收
global $link;
$time=time()-$lifetime; //垃圾时间的临界点
$sql="delete from sess where sess_time<$time";
return mysqli_query($link,$sql);
}
}
session_set_save_handler('open','close','read','write','destroy','gc');
session_start();
$_SESSION['name']='tom';
//session_destroy();
网友评论