您的位置:首页 > 编程语言 > PHP开发

php中使用session_set_save_handler(),session入库(mysql)机制

2016-11-04 15:00 861 查看
seesion的入库(mysql)操作,主要是修改seesion的读取与写入操作

主要是通过 bool session_set_save_handler(seesion_open,seesion_close,session_read,session_write,session_destory,session_gc);

依次对应的是开启seesion连接方式,关闭session,读取session,写拉seesion,销毁session,seesion的垃圾加收机制。

基本实例项目

<?php

/*
建表字段类型
create table session (
9 sess_id char(32) UNIQUE NOT NULL,
10 sess_info text,
11 sess_expire int not null default 0
12 )CHARSET utf8 ENGINE INNODB;

*/

class FileSessionHandler
{
private $savePath;
public $pdo;
//session入库
//1. 开启session
function open($savePath, $sessionName)
{
//连接mysql
$this->pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
$this->pdo->exec("set names utf8");
//查看当前调用了什么方法
//echo __FUNCTION__.'<br/>';
}
//2. 关闭session
function close()
{
//关闭mysql
$this->pdo = null;
//echo __FUNCTION__.'<br/>';
return true;
}
//3. 读取session
function read($id)
{
//从数据库读取

$sql = "select * from session where sess_id = '$id'";
//得到一个数组
$res = $this->pdo->query($sql)->fetch(PDO::FETCH_ASSOC);
//echo __FUNCTION__.'<br/>';
return $res['sess_info'];
}
// 4.写入操作
function write($id, $data)
{
//使用replace主是要因为要重复修改seesion,而sess_id又是UNIQUE
$time = time();
$sql = "replace into session values('$id','$data','$time')";
//echo __FUNCTION__.'<br>';
return $res = $this->pdo->exec($sql);

}
//5. 销毁
function destroy($id)
{
//删除数据库中信息
$sql = "delete from session where sess_id = '$id'";
//echo __FUNCTION__.'<br>';
return $res = $this->pdo->exec($sql);
}
//6.回收
function gc()
{
//删除过期的数据
/*$expire = time()-ini_get('session.gc_maxlifetime');
$sql = "delete from session where sess_expire < '{$expire}'";
    return $this->pdo->exec($sql);*/
//echo __FUNCTION__.'<br>';
}

}

以下用于外部实例调用:
注:外部调用需引入以上类文件

/**
* 以下用于外部调用
*/
$handler = new FileSessionHandler();
//修改session机制
session_set_save_handler(
array($handler, 'open'),
array($handler, 'close'),
array($handler, 'read'),
array($handler, 'write'),
array($handler, 'destroy'),
array($handler, 'gc')
);

// 下面这行代码可以防止使用对象作为会话保存管理器时可能引发的非预期行为
//register_shutdown_function('session_write_close');

// 现在可以使用 $_SESSION 保存以及获取数据了
session_start();//开启session
$_SESSION['sess_info']='632275220';
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  php session 函数 class 实例