SessionHandler.php文件内容如下
<?php
namespace Dry\Base;
class SessionHandler{
private $pdo = null;
private $lifeTime = 1440;
public function __construct($pdo)
{
$this->pdo = $pdo;
$this->lifeTime = get_cfg_var('session.gc_maxlifetime');
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
register_shutdown_function('session_write_close');
}
public function open($save_path, $session_name)
{
return true;
}
public function close()
{
return true;
}
public function read($session_id)
{
$time = date('Y-m-d H:i:s');
$sql = "select session_data from session_handler where session_id='{$session_id}' and session_expires>'{$time}' limit 1";
$sm = $this->pdo->prepare($sql);
$sm->execute();
if($sm->rowCount()){
$result = $sm->fetch();
return $result['session_data'];
}
else{
return '';
}
}
public function write($session_id, $session_data)
{
$time = date('Y-m-d H:i:s', time()+$this->lifeTime);
$sql = "select count(1) as total from session_handler where session_id='{$session_id}' limit 1";
$sm = $this->pdo->prepare($sql);
$sm->execute();
if($sm->fetchColumn()){
$sql="update session_handler set session_data='{$session_data}',session_expires='{$time}' where session_id='{$session_id}'";
}
else{
$sql="insert into session_handler(session_id,session_data,session_expires) values('{$session_id}','{$session_data}','{$time}')";
}
$sm = $this->pdo->prepare($sql);
$sm->execute();
return true;
}
public function destroy($session_id)
{
$sql = "delete from session_handler where session_id='{$session_id}'";
$sm = $this->pdo->prepare($sql);
$sm->execute();
return true;
}
public function gc($maxlifetime)
{
$time = date('Y-m-d H:i:s', time()-$maxlifetime);
$sql = "delete from session_handler where session_expires<'{$time}'";
$sm = $this->pdo->prepare($sql);
$sm->execute();
return true;
}
}
?>
test.php文件内容如下
<?php
require_once('SessionHandler.php');
use Dry\Base\SessionHandler;
$pdo = new PDO('mysql:host=192.168.1.20;dbname=test;port=3306', 'root', '1234', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8',
PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
new SessionHandler($pdo);
session_start();
$_SESSION['name'] = 'test';
echo $_SESSION['name'];
?>
session_handler表结构如下
CREATE TABLE `session_handler` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`session_id` varchar(64) NOT NULL,
`session_data` mediumtext,
`session_expires` datetime NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `session_id` (`session_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
- 5 回答
- 0 关注
- 446 浏览
添加回答
举报
0/150
提交
取消