session_set_save_handler函数
PHP的session_set_save_handler
函数用来定义用户级session保存函数(如打开、关闭、写入等)。原型如下:
bool session_set_save_hanler(callback open,callback close,callback read,callback write,callback destory,callback gc)
Session管理类
找到PHP的配置文件php.ini,修改为下面内容,保存并重启php-fpm服务。
session.save_handler = redis
我们编写一个用来管理session的类:
<?php
class SessionManager{
private $redis;
private $sessionSavePath;
private $sessionName;
private $sessionExpireTime = 60;//redis,session的过期时间为30s
public function __construct(){
$this->redis = new Redis();//创建phpredis实例
$this->redis->connect('127.0.0.1', 6379);//连接redis
//$this->redis->auth("123456x");//授权
$retval = session_set_save_handler(
array($this,"open"),
array($this,"close"),
array($this,"read"),
array($this,"write"),
array($this,"destroy"),
array($this,"gc")
);
session_start();
}
public function open($path,$name){
return true;
}
public function close(){
return true;
}
public function read($id){
$value = $this->redis->get($id);//获取redis中的指定记录
if($value){
return $value;
}else{
return '';
}
}
public function write($id,$data){
if($this->redis->set($id,$data)){//以session ID为键,存储
$this->redis->expire($id,$this->sessionExpireTime);//设置redis中数据的过期时间,即session的过期时间
return true;
}
return false;
}
public function destroy($id){
if($this->redis->delete($id)){//删除redis中的指定记录
return true;
}
return false;
}
public function gc($maxlifetime){
return true;
}
public function __destruct(){
session_write_close();
}
}
SessionManager构造函数主要用来连接Redis服务器,使用session_set_save_handler
函数设置session回调函数,并调用session_start
函数开启session功能。因为本例中open
、close
和gc
回调函数的作用不是很大,所以直接返回true。
在write回调函数中,以session ID 作为key,把session的数据作为value存储到redis服务器,设置session的过期时间为30秒。在read 回调函中,以session ID 作为key从redis服务器中读取数据,并返回此数据。而在destroy
回调函数重,则以session ID 作为key 从redis服务器中删除对应的session数据。
使用Session
先建立一个set.php文件,用来设置Session:
<?php
require_once 'SessionManager.php';
new SessionManager();
$_SESSION['username'] = 'helloweba';
然后建立get.php文件,用来获取Session:
<?php
require_once 'SessionManager.php';
new SessionManager();
echo $_SESSION['username'];
很显然,我们先包含session管理类,然后实例化后就可以使用PHP正常的session函数了。
测试时,首先访问set.php,然后再访问get.php,输出结果如下所示:
最后,我们到redis里查看结果:
声明:本文为原创文章,http://helloweba.net和作者拥有版权,如需转载,请注明来源于helloweba.net并保留原文链接:https://www.helloweba.net/php/616.html