Redis alternate file storage session in PHP

Source: Internet
Author: User
Tags session id php class redis redis server

PHP defaults to using file storage session, if the concurrent volume is large, the efficiency is very low. and Redis support for high concurrency is excellent, so you can use Redis instead of file storage session.

Here, introduce the function of PHP Session_set_save_handler function and use method. This function defines a user-level session save function (such as open, close, write, and so on). The prototype is as follows:

BOOL Session_set_save_hanler (callback Open,callback close,callback read,callback write,callback destory,callback GC)

The Session_set_save_handler function parameters function as follows table

Parameters Description
Open This function is called when session is open. Receives two parameters, the first parameter is the path that holds the session, and the second parameter is the name of the session
Close This function is called when the session operation completes. No parameters are received.
Read Takes the session ID as an argument. The data is obtained from the data store by the session ID and returned. If the data is empty, you can return an empty string. This function is triggered before calling Session_Start
Write Called when data is stored. There are two parameters, one is the session ID, the other is the session data
Destroy The Destroy function is triggered when the Session_destroy function is invoked. 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 for the php.ini configuration file to user, otherwise the session_set_save_handle will not take effect.

Write a session management class sessionmanager.php with the following code:

<?php class sessionmanager{Private $redis;
    Private $sessionSavePath;
    Private $sessionName; Private $sessionExpireTime =30;//redis,session expires in 30s public function __construct () {$this->redis = new R Edis ()///Create Phpredis instance $this->redis->connect (' 127.0.0.1 ', 6379);//Connect Redis $this->redis->auth ("10 
            7lab ")//Authorization $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 ();
    The Public function open ($path, $name) {return true;
    The public function close () {true;
            The public function read ($id) {$value = $this->redis->get ($id);//Get the specified record in Redis if ($value) {
        return $value;
        }else{return "; }} public Function write ($id, $data) {if ($this->redis->set ($id, $data)) {//The session ID is the key, stored $this->redis->expire ($id, $
        This->sessionexpiretime)//sets the expiration time of the data in the Redis, that is, the session expiration return true;
    return false;
        The Public function destroy ($id) {if ($this->redis->delete ($id)) {//delete the specified record in the Redis return true;
    return false;
    The Public Function gc ($MAXLIFETIME) {return true;
    Public Function __destruct () {session_write_close ();
 }

}

The SessionManager constructor is primarily used to connect the Redis server, set the session callback function using the Session_set_save_handler function, and invoke the Session_Start function to open the session function. Because the open, close, and GC callback functions in this example are not very large, return true directly.

In the write callback function, with the session ID as the key, the session's data is stored as value to the Redis server, and the session expiration is set to 30 seconds. In the read callback, reads the data from the Redis server with the session ID as key and returns this data. When the destroy callback function is heavy, the corresponding session data is deleted from the Redis server with the session ID as key.

When used, simply include the SessionManager class, and then instantiate a SessionManager object. Create a session_set.php file below. Input code

<?php
    include (' sessionmanager.php ');
    New SessionManager ();
    $_session[' username '] = ' Captain ';

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

<?php
    include (' sessionmanager.php ');
    New SessionManager ();
    echo $_session[' username '];

When you test, you first access session_set.php and then access session_get.php, and the output looks like this:

Look at the Redis database again, as shown below

127.0.0.1:6379> keys * 1) "oe94eic337slnjv1bvlreoa574" 127.0.0.1:6379> get oe94eic337slnjv1bvlreoa574 "username|s:7:\" captain\ ";" 
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.