Home > Backend Development > PHP Tutorial > PHP uses Redis instead of file to store Session

PHP uses Redis instead of file to store Session

墨辰丷
Release: 2023-03-27 22:34:02
Original
1856 people have browsed it

This article mainly introduces how PHP uses Redis instead of files to store Sessions. It analyzes the basic operation methods of Sessions and related techniques of using Redis to store sessions in detail in the form of examples. Friends in need can refer to it

The example in this article describes how PHP uses Redis instead of file storage to store Session. Share it with everyone for your reference, the details are as follows:

PHP uses files to store sessions by default. If the amount of concurrency is large, the efficiency is very low. And Redis supports high concurrency very well, so you can use redis instead of file storage session.

Here, introduce the function and usage of php's session_set_save_handler function. This function defines user-level session saving functions (such as open, close, write, etc.).

The prototype is as follows:

bool session_set_save_hanler(callback open,callback close,callback read,callback write,callback destory,callback gc)

## The functions of each parameter of the #session_set_save_handler function are as follows


##openCalled when session is opened this function. Receives two parameters. The first parameter is the path to maintain the session. The second parameter is the name of the session. closeThis function is called when the session operation is completed. . Does not receive parameters. read takes session ID as parameter. Obtain data from the data storage party through the session ID and return this data. If the data is empty, an empty string can be returned. This function is triggered before calling writeCalled when data is stored .There are two parameters, one is the session ID, the other is the session data
Parameters Description
session_start<span style="font-family:新宋体"></span>
destroy When calling<span style="font-family:新宋体">session_destroy</span> The destroy function is triggered when the function is executed. There is only one parameter session ID
gc Triggered when PHP executes the session garbage collection mechanism


Before using this function, set the session.save_handler option in the php.ini configuration file to user, otherwise session_set_save_handle will not take effect.

Write a session management class sessionManager.php, the code is as follows:

<?php
class SessionManager{
 private $redis;
 private $sessionSavePath;
 private $sessionName;
 private $sessionExpireTime=30;//redis,session的过期时间为30s
 public function __construct(){
 $this->redis = new Redis();//创建phpredis实例
 $this->redis->connect(&#39;127.0.0.1&#39;,6379);//连接redis
 $this->redis->auth("107lab");//授权
 $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 &#39;&#39;;
 }
 }
 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();
 }
}
Copy after login

The SessionManager constructor is mainly used to connect to the Redis server. Use the session_set_save_handler function to set the session callback function, and call the session_start function to enable the session function. Because the open, close and gc callback functions in this example are not very useful, they return true directly.

In the write callback function, use the session ID as the key, store the session data as the value in the redis server, and set the session expiration time to 30 seconds. In the read callback function, use the session ID as the key to read data from the redis server and return this data. In the destroy callback function, the session ID is used as the key to delete the corresponding session data from the redis server.

When using it, just include the SessionManager class and then instantiate a SessionManager object. Create a session_set.php file below. Enter the code

<?php
 include(&#39;SessionManager.php&#39;);
 new SessionManager();
 $_SESSION[&#39;username&#39;] = &#39;captain&#39;;
Copy after login

and then create a session_get.php file and enter the following code:

<?php
 include(&#39;SessionManager.php&#39;);
 new SessionManager();
 echo $_SESSION[&#39;username&#39;];
Copy after login

When testing, first access session_set.php, and then access session_get.php. The output result is as follows:

Then check the redis database, as shown below

127.0.0.1:6379> keys *
1) "oe94eic337slnjv1bvlreoa574"
127.0.0.1:6379> get oe94eic337slnjv1bvlreoa574
"username|s:7:\"captain\";"
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone's study.


Related recommendations:

PHP method to obtain a 6-digit random number that does not exist in redis

PHP implementationredisMessage queue publishing Weibo method

CI framework (CodeIgniter) operationredisStep analysis

The above is the detailed content of PHP uses Redis instead of file to store Session. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template