自定义 Session 数据保存
当项目访问量大的时候,我们就不能采取php默认session存储方式了(php默认为文件存储),这个时候我们就要自己实现session数据存储。好在php提供了重写session数据的接口给我们。下面就是简单的用mysql存储session数据案例。
<?php
/**
* @Author: Aaron
* @Last Modified by: Aaron
*/
class MysqlSessionHandle implements SessionHandlerInterface
{
protected $_pdo = null;
public function close()
{
$this->_pdo = null;
}
public function destroy($sessionID)
{
$sql = "delete from session where id = :sessionID";
$stm = $this->_pdo->prepare($sql);
$stm->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
$stm->execute();
}
public function gc($maxlifetime)
{
$sql = "delete from session where createTime < :maxlifetime";
$stm = $this->_pdo->prepare($sql);
@$stm->bindParam(':maxlifetime',$maxlifetime,PDO::PARAM_INT);
$stm->execute();
}
public function open($savePath,$sessionName)
{
$dsn = 'mysql:dbname=test;host=127.0.0.1';
$user = 'root';
$password = 123456;
try {
$this->_pdo = new PDO($dsn,$user,$password);
} catch (\Exception $e) {
// 连接异常 可以在次记录日志
}
}
public function read($sessionID)
{
$sql = "select * from session where id = :sessionID";
$sth = $this->_pdo->prepare($sql);
$sth->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result['data'];
}
public function write($sessionID,$data)
{
$sql = 'select * from session where id = :sessionid';
$sth = $this->_pdo->prepare($sql);
$sth->bindParam(':sessionid',$sessionID,PDO::PARAM_STR,strlen($sessionID));
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
if (empty($result)) {
$sql = "insert into session values(:sessionID , :data , :time)";
}else{
$sql = "update session set data = :data, createTime = :time where id = :sessionID";
}
$sth = $this->_pdo->prepare($sql);
// 绑定参数值 并 设定参数类型
$sth->bindParam(':sessionID',$sessionID,PDO::PARAM_STR,strlen($sessionID));
@$sth->bindParam(':time',time());
$sth->bindParam(':data',$data,PDO::PARAM_STR,strlen($data));
$result = $sth->execute();
}
}
$myse = new MysqlSessionHandle();
session_set_save_handler($myse,true);
session_start();
$_SESSION['name'] = 'Aaron';
$_SESSION['age'] = 27;
$_SESSION['profession'] = 'PHP工程师';