Home Backend Development PHP Tutorial Put session into cache (redis), DB

Put session into cache (redis), DB

Aug 08, 2016 am 09:30 AM
handler redis session

Why should SESSION be saved in cache

 As far as PHP is concerned, the session supported by the language itself is saved to a disk file in the form of a file and saved in a specified folder. The saved path can be set in the configuration file or using the function session_save_path() in the program. , but there are disadvantages to doing so,

The first is to save it to the file system, which is inefficient. As long as the session is used, the specified sessionid will be searched from multiple files, which is very inefficient.

The second is that when using multiple servers, the problem of session loss may occur (actually it is saved on other servers).

 Of course, saving in the cache can solve the above problem. If you use PHP's own session function, you can use the session_set_save_handler() function to easily re-control the session processing process. If you don't use PHP's session series functions, you can write a similar session function yourself. It's also possible. This is the project I'm working on now. It will calculate the hash as the sessionId based on the user's mid and login time. Each time it is requested, The sessionId must be added to be legal (it is not needed when logging in for the first time, the sessionId will be created at this time and returned to the client). This is also very convenient, concise and efficient. Of course, what I am mainly talking about in this article is "manipulating things" in PHP's own SESSION.

SESSION saved in cache

  PHP saves the cache to redis. You can use the configuration file to modify the processing and saving of the session. Of course, you can also use the ini_set() function in the program to modify it. This is very convenient for testing. I will use this here. Method, of course, it is recommended to use configuration files in a production environment.

<?<span>php
</span><span>ini_set</span>("session.save_handler", "redis"<span>);
</span><span>ini_set</span>("session.save_path", "tcp://localhost:6379"<span>);
</span><span>session_start</span><span>();
</span><span>header</span>("Content-type:text/html;charset=utf-8"<span>);
</span><span>if</span>(<span>isset</span>(<span>$_SESSION</span>['view'<span>])){
    </span><span>$_SESSION</span>['view'] = <span>$_SESSION</span>['view'] + 1<span>;
}</span><span>else</span><span>{
    </span><span>$_SESSION</span>['view'] = 1<span>;
}
</span><span>echo</span> "【view】{<span>$_SESSION</span>['view']}";
Copy after login

Here, set the session.save_handler method to redis, and session.save_path to the address and port of redis. After setting, refresh, and then look back at redis. You will find that the sessionId is generated in redis, and the sessionId is the same as the one requested by the browser.

Isn’t it very convenient? You only need to change the configuration file to save the session in redis. But what I want to talk about here is to use the program to save the session to redis or db. Let’s take a look.

Rewrite the session processing function by yourself through the interface provided by php

Here you can first take a look at the function session_set_save_handler in PHP. PHP5.4 and later can directly implement the SessionHandlerInterface interface, and the code will be more concise. When rewriting, there are mainly the following methods

open(string $savePath, string $sessionName); //open is similar to a constructor and will be called when starting a session, such as after using the session_start() function

close(); //Similar to the destructor of a class, it is called after the write function is called, and will also be executed after session_write_close()

read(string $sessionId); //Called when reading session

write(string $sessionId, string $data); //Called when saving data

destory($sessionId); //When destroying the session (session_destory() or session_regenerate_id()) it will be called

gc($lifeTime); //Garbage cleaning function to clean up expired data

 The main thing is to implement these methods. You can set different specific methods according to different storage drivers. I have implemented mysql database and redis, two drivers for saving sessions. If necessary, you can expand it yourself. Expansion is very convenient and very convenient. easy.

The following is my redis implementation (db is similar to redis, redis code is less, posted here):

I used the interface method, which makes it easier to expand. I wanted to use memcached that day, so just add it directly

<?<span>php
</span><span>include_once</span> __DIR__."/interfaceSession.php"<span>;
</span><span>/*</span><span>*
 * 以db的方式存储session
 </span><span>*/</span>
<span>class</span> redisSession <span>implements</span><span> interfaceSession{
    </span><span>/*</span><span>*
     * 保存session的数据库表的信息
     </span><span>*/</span>
    <span>private</span> <span>$_options</span> = <span>array</span><span>(
        </span>'handler' => <span>null</span>, <span>//</span><span>数据库连接句柄</span>
        'host' => <span>null</span>,
        'port' => <span>null</span>,
        'lifeTime' => <span>null</span>,<span>
    );

    </span><span>/*</span><span>*
     * 构造函数
     * @param $options 设置信息数组
     </span><span>*/</span>
    <span>public</span> <span>function</span> __construct(<span>$options</span>=<span>array</span><span>()){
        </span><span>if</span>(!<span>class_exists</span>("redis", <span>false</span><span>)){
            </span><span>die</span>("必须安装redis扩展"<span>);
        }
        </span><span>if</span>(!<span>isset</span>(<span>$options</span>['lifeTime']) || <span>$options</span>['lifeTime'] <= 0<span>){
            </span><span>$options</span>['lifeTime'] = <span>ini_get</span>('session.gc_maxlifetime'<span>);
        }
        </span><span>$this</span>->_options = <span>array_merge</span>(<span>$this</span>->_options, <span>$options</span><span>);
    }

    </span><span>/*</span><span>*
     * 开始使用该驱动的session
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> begin(){
        </span><span>if</span>(<span>$this</span>->_options['host'] === <span>null</span> ||
           <span>$this</span>->_options['port'] === <span>null</span> ||
           <span>$this</span>->_options['lifeTime'] === <span>null</span><span>
        ){
            </span><span>return</span> <span>false</span><span>;
        }
        </span><span>//</span><span>设置session处理函数</span>
        <span>session_set_save_handler</span><span>(
            </span><span>array</span>(<span>$this</span>, 'open'),
            <span>array</span>(<span>$this</span>, 'close'),
            <span>array</span>(<span>$this</span>, 'read'),
            <span>array</span>(<span>$this</span>, 'write'),
            <span>array</span>(<span>$this</span>, 'destory'),
            <span>array</span>(<span>$this</span>, 'gc'<span>)
        );
    }
    </span><span>/*</span><span>*
     * 自动开始回话或者session_start()开始回话后第一个调用的函数
     * 类似于构造函数的作用
     * @param $savePath 默认的保存路径
     * @param $sessionName 默认的参数名,PHPSESSID
     </span><span>*/</span>
    <span>public</span> <span>function</span> open(<span>$savePath</span>, <span>$sessionName</span><span>){
        </span><span>if</span>(<span>is_resource</span>(<span>$this</span>->_options['handler'])) <span>return</span> <span>true</span><span>;
        </span><span>//</span><span>连接redis</span>
        <span>$redisHandle</span> = <span>new</span><span> Redis();
        </span><span>$redisHandle</span>->connect(<span>$this</span>->_options['host'], <span>$this</span>->_options['port'<span>]);
        </span><span>if</span>(!<span>$redisHandle</span><span>){
            </span><span>return</span> <span>false</span><span>;
        }

        </span><span>$this</span>->_options['handler'] = <span>$redisHandle</span><span>;
        </span><span>$this</span>->gc(<span>null</span><span>);
        </span><span>return</span> <span>true</span><span>;

    }

    </span><span>/*</span><span>*
     * 类似于析构函数,在write之后调用或者session_write_close()函数之后调用
     </span><span>*/</span>
    <span>public</span> <span>function</span><span> close(){
        </span><span>return</span> <span>$this</span>->_options['handler']-><span>close();
    }

    </span><span>/*</span><span>*
     * 读取session信息
     * @param $sessionId 通过该Id唯一确定对应的session数据
     * @return session信息/空串
     </span><span>*/</span>
    <span>public</span> <span>function</span> read(<span>$sessionId</span><span>){
        </span><span>return</span> <span>$this</span>->_options['handler']->get(<span>$sessionId</span><span>);
    }

    </span><span>/*</span><span>*
     * 写入或者修改session数据
     * @param $sessionId 要写入数据的session对应的id
     * @param $sessionData 要写入的数据,已经序列化过了
     </span><span>*/</span>
    <span>public</span> <span>function</span> write(<span>$sessionId</span>, <span>$sessionData</span><span>){
        </span><span>return</span> <span>$this</span>->_options['handler']->setex(<span>$sessionId</span>, <span>$this</span>->_options['lifeTime'], <span>$sessionData</span><span>);
    }

    </span><span>/*</span><span>*
     * 主动销毁session会话
     * @param $sessionId 要销毁的会话的唯一id
     </span><span>*/</span>
    <span>public</span> <span>function</span> destory(<span>$sessionId</span><span>){
        </span><span>return</span> <span>$this</span>->_options['handler']->delete(<span>$sessionId</span>) >= 1 ? <span>true</span> : <span>false</span><span>;
    }

    </span><span>/*</span><span>*
     * 清理绘画中的过期数据
     * @param 有效期
     </span><span>*/</span>
    <span>public</span> <span>function</span> gc(<span>$lifeTime</span><span>){
        </span><span>//</span><span>获取所有sessionid,让过期的释放掉</span>
        <span>$this</span>->_options['handler']->keys("*"<span>);
        </span><span>return</span> <span>true</span><span>;
    }

}</span>
Copy after login

Look at the simple factory pattern

<span>class</span><span> session {
    </span><span>/*</span><span>*
     * 驱动程序句柄保存
     </span><span>*/</span>
    <span>private</span> <span>static</span> <span>$_handler</span> = <span>null</span><span>;

    </span><span>/*</span><span>*
     * 创建session驱动程序
     </span><span>*/</span>
    <span>public</span> <span>static</span> <span>function</span> getSession(<span>$type</span>, <span>$options</span><span>){
        </span><span>//</span><span>单例</span>
        <span>if</span>(<span>isset</span>(<span>$handler</span><span>)){
            </span><span>return</span> self::<span>$_handler</span><span>;
        }

        </span><span>switch</span> (<span>$type</span><span>) {
            </span><span>case</span> 'db': <span>//</span><span>数据库驱动session类型</span>
                    <span>include_once</span> __DIR__."/driver/dbSession.php"<span>;
                    </span><span>$handler</span> = <span>new</span> dbSession(<span>$options</span><span>);
                </span><span>break</span><span>;
            
            </span><span>case</span> 'redis': <span>//</span><span>redis驱动session类型</span>
                    <span>include_once</span> __DIR__."/driver/redisSession.php"<span>;
                    </span><span>$handler</span> = <span>new</span> redisSession(<span>$options</span><span>);
                </span><span>break</span><span>;
            </span><span>default</span>:
                    <span>return</span> <span>false</span><span>;
                </span><span>break</span><span>;
        }

        </span><span>return</span> self::<span>$_handler</span> = <span>$handler</span><span>;
    }
}</span>
Copy after login

 Calling is also very simple,

session::getSession('redis',<span>array</span><span>(
        </span>'host' => "localhost",
        'port' => "6379",<span>
    ))</span>-><span>begin();

</span><span>session_start</span>();
Copy after login

 The database version is also very simple to configure. If necessary, you can download the full version and demo here

 The copyright of this article belongs to the author iforever (luluyrt@163.com). Any form of reprinting is prohibited without the author's consent. After reprinting the article, the author and the original text link must be provided in an obvious position on the article page, otherwise the right to pursue legal liability is reserved. .

The above introduces the session into cache (redis) and DB, including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to build the redis cluster mode How to build the redis cluster mode Apr 10, 2025 pm 10:15 PM

Redis cluster mode deploys Redis instances to multiple servers through sharding, improving scalability and availability. The construction steps are as follows: Create odd Redis instances with different ports; Create 3 sentinel instances, monitor Redis instances and failover; configure sentinel configuration files, add monitoring Redis instance information and failover settings; configure Redis instance configuration files, enable cluster mode and specify the cluster information file path; create nodes.conf file, containing information of each Redis instance; start the cluster, execute the create command to create a cluster and specify the number of replicas; log in to the cluster to execute the CLUSTER INFO command to verify the cluster status; make

How to read redis queue How to read redis queue Apr 10, 2025 pm 10:12 PM

To read a queue from Redis, you need to get the queue name, read the elements using the LPOP command, and process the empty queue. The specific steps are as follows: Get the queue name: name it with the prefix of "queue:" such as "queue:my-queue". Use the LPOP command: Eject the element from the head of the queue and return its value, such as LPOP queue:my-queue. Processing empty queues: If the queue is empty, LPOP returns nil, and you can check whether the queue exists before reading the element.

How to clear redis data How to clear redis data Apr 10, 2025 pm 10:06 PM

How to clear Redis data: Use the FLUSHALL command to clear all key values. Use the FLUSHDB command to clear the key value of the currently selected database. Use SELECT to switch databases, and then use FLUSHDB to clear multiple databases. Use the DEL command to delete a specific key. Use the redis-cli tool to clear the data.

How to configure Lua script execution time in centos redis How to configure Lua script execution time in centos redis Apr 14, 2025 pm 02:12 PM

On CentOS systems, you can limit the execution time of Lua scripts by modifying Redis configuration files or using Redis commands to prevent malicious scripts from consuming too much resources. Method 1: Modify the Redis configuration file and locate the Redis configuration file: The Redis configuration file is usually located in /etc/redis/redis.conf. Edit configuration file: Open the configuration file using a text editor (such as vi or nano): sudovi/etc/redis/redis.conf Set the Lua script execution time limit: Add or modify the following lines in the configuration file to set the maximum execution time of the Lua script (unit: milliseconds)

How to use the redis command line How to use the redis command line Apr 10, 2025 pm 10:18 PM

Use the Redis command line tool (redis-cli) to manage and operate Redis through the following steps: Connect to the server, specify the address and port. Send commands to the server using the command name and parameters. Use the HELP command to view help information for a specific command. Use the QUIT command to exit the command line tool.

How to set the redis expiration policy How to set the redis expiration policy Apr 10, 2025 pm 10:03 PM

There are two types of Redis data expiration strategies: periodic deletion: periodic scan to delete the expired key, which can be set through expired-time-cap-remove-count and expired-time-cap-remove-delay parameters. Lazy Deletion: Check for deletion expired keys only when keys are read or written. They can be set through lazyfree-lazy-eviction, lazyfree-lazy-expire, lazyfree-lazy-user-del parameters.

How to optimize the performance of debian readdir How to optimize the performance of debian readdir Apr 13, 2025 am 08:48 AM

In Debian systems, readdir system calls are used to read directory contents. If its performance is not good, try the following optimization strategy: Simplify the number of directory files: Split large directories into multiple small directories as much as possible, reducing the number of items processed per readdir call. Enable directory content caching: build a cache mechanism, update the cache regularly or when directory content changes, and reduce frequent calls to readdir. Memory caches (such as Memcached or Redis) or local caches (such as files or databases) can be considered. Adopt efficient data structure: If you implement directory traversal by yourself, select more efficient data structures (such as hash tables instead of linear search) to store and access directory information

How to implement redis counter How to implement redis counter Apr 10, 2025 pm 10:21 PM

Redis counter is a mechanism that uses Redis key-value pair storage to implement counting operations, including the following steps: creating counter keys, increasing counts, decreasing counts, resetting counts, and obtaining counts. The advantages of Redis counters include fast speed, high concurrency, durability and simplicity and ease of use. It can be used in scenarios such as user access counting, real-time metric tracking, game scores and rankings, and order processing counting.

See all articles