参考文档https://blog.csdn.net/lipeigang1109/article/details/78664234
这是一个直接封装好的类,复制粘贴即可使用(标红的修改成自己的)。
强调一点,必须装了redis的扩展才可使用(我安装的是lnmp.org 地址https://lnmp.org/faq/addons.html)
class RedisSession implements SessionHandlerInterface
{
private $handle;
private $lifetime;
private $prefix = 'PHPSESSID:';
/**
* open session
* @param string $save_path
* @param string $session_name
* @return bool
*/
public function open($save_path, $session_name)
{
$this->handle = new Redis();
$this->handle->connect('r-2zef1d24c420b1f4.redis.rds.aliyuncs.com', '6379');//阿里的服务器,网址+端口
// redis 密码
$this->handle->auth('******');//密码
$this->handle->select('101');//第几个数据库,按需求让使用第几个改为几就行
// 过期时间设置
$this->lifetime = ini_get('session.gc_maxlifetime');
return true;
}
/**
* close session
* @return bool
*/
public function close()
{
$this->gc($this->lifetime);
$this->handle->close();
$this->handle = null;
return true;
}
/**
* read session by session_id
* @param string $session_id
* @return mixed
*/
public function read($session_id)
{
$session_id = $this->prefix . $session_id;
$data = $this->handle->get($session_id);
$this->handle->expire($session_id, $this->lifetime);
return $data;
}
/**
* write session by session_id
* @param string $session_id
* @param string $session_data
* @return mixed
*/
public function write($session_id, $session_data)
{
$session_id = $this->prefix . $session_id;
$this->handle->set($session_id, $session_data);
return $this->handle->expire($session_id, $this->lifetime);
}
/**
* delete session_id
* @param string $session_id
* @return mixed
*/
public function destroy($session_id)
{
return $this->handle->rm($this->prefix . $session_id);
}
/**
* this function is no use because of redis expire
* @param int $maxlifetime
* @return bool
*/
public function gc($maxlifetime)
{
return true;
}
}
$handler = new RedisSession();
// 设置用户自定义会话存储函数
session_set_save_handler($handler, true);
register_shutdown_function('session_write_close');
session_start();
$session = $_SESSION['test'] = 'test';
var_dump($session);