


PHP implements Session storage to Redis, sessionredis_PHP tutorial
PHP implements Session storage in Redis, sessionredis
It is not appropriate to use the default Session for sites with large visits. We can store it in the database or use Redis KEY- VALUE data storage solution
First create a new session table
CREATE TABLE `sessions` ( `sid` char(40) NOT NULL, `updatetime` int(20) NOT NULL, `data` varchar(200) NOT NULL, UNIQUE KEY `sid` (`sid`) USING HASH ) ENGINE=MEMORY DEFAULT CHARSET=utf8;
Mysql’s memory engine uses memory tables, all data is stored in memory, and the operation speed is fast
<?php //引入数据库文件 include "db.php"; class MySessionHandler implements SessionHandlerInterface { private $savePath; private $sessData; public $expiretime; //设置过期时间 public $db; //数据库 public function __construct($hanlder =''){ $this->db = Database::getInstance(); //获取数据库实力 ///var_dump($this->db); } public function open($savePath, $sessionName) { return true; } public function close() { return true; } public function read($id) { $sql ="select * from sessions where sid ='$id'"; $result = $this->db->execute($sql); if(!empty($result)){ return $this->sessData = $result; } } //函数的参数 $id -> 当前会话ID //数据DATA -> 序列化之后的字符串 public function write($id, $data) { // echo $id; // echo $data; $now = time(); $newExp = $now+$this->expiretime; //总时间=当前时间 + 期限时间 $sql = "select * from sessions where sid ='$id'"; $result = $this->db->getOne($sql); //var_dump($result); if($data==''||isset($data)){ $data = $this->sessData; } if($result){ //如果存在则更新 $sql ="update sessions set updatetime = '$newExp',data ='$data' where sid = '$id'"; //echo $sql; $update_data =$this->db->execute($sql); if($update_data){ return true; } }else{ //不存在则生成生成 $sql = "insert into sessions(sid,updatetime,data) values('$id','$now','$data')"; $insert_data = $this->db->execute($sql); if($insert_data){ return true; } } return false; } public function destroy($id) { //销毁 $sql = "delete from sessions where sid="."$id"; $destory = $this->db->execute($sql); if($destory){ return true; }else{ return false; } } public function gc($sessMaxLifeTime) { $t = time(); $sql ="delete from sessions where $t - 'updatetime'>${sessMaxLifeTime}"; $data = $this->db->execute($this->tosql); if($data){ return true; }else{ return false; } return true; } }
Instantiation
There are two methods for PHP manual here
1. An object that implements the SessionHandlerInterface interface and can be used since PHP5.4
2. Use session_set_save_handler
directly
//判断PHP版本 if(version_compare(PHP_VERSION,5.4)==1){ session_set_save_handler($handler, true); session_start(); }else{ ini_set('session.use_trans_sid',0); ini_set('session.use_cookies',1); ini_set('session.cookie_path','/'); ini_set('session.save_handler','user'); session_module_name('user'); session_set_save_handler(array($session,"open"),array($session,"close"),array($session,"read"),array($session,"write"),array($session,"destory"),array($session,"gc")); session_start(); } $_SESSION['QQ']="QQ"; echo $_SESSION['QQ'];
Database code
<?php class Database{ static $instance; static $db; static function getInstance(){ if(self::$instance){ return self::$instance; }else{ return new Database(); } } public function __construct(){ self::$db = new PDO('mysql:host=localhost;dbname=session', 'root',''); } public function getOne($sql){ $rs =self::$db->query($sql); @$rs->setFetchMode(PDO::FETCH_ASSOC);//返回关联数组 $result = $rs -> fetch(); return $result; } public function execute($sql){ $rs = self::$db->exec($sql); return $rs; } } //$data = Database::getInstance(); //var_dump($data);
Use REDIS to store SESSION
<?php class SessionManager{ private $redis; private $sessionSavePath; private $sessionName; private $sessionExpireTime = 30; public function __construct(){ $this->redis = new Redis(); $this->redis->connect('127.0.0.1',6379); //连接redis $retval = session_set_save_handler( array($this,"open"), array($this,"close"), array($this,"read"), array($this,"write"), array($this,"destory"), 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); if($value){ return $value; }else{ return ""; } } public function write($id,$data){ if($this->redis->set($id,$data)){ $this->redis->expire($id,$this->sessionExpireTime); //设置过期时间 return true; } return false; } public function destory($id){ if($this->redis->delete($id)){ return true; } return false; } public function gc($maxlifetime){ return true; } //析构函数 public function __destruct(){ session_write_close(); } } $re = new SessionManager(); $_SESSION['name'] = "qq"; echo $_SESSION['name'];
The above is a detailed introduction to the method of storing Session to Redis in PHP. I hope it will be helpful to everyone's learning.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Validator can be created by adding the following two lines in the controller.

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an
