How the session in PHP is stored in Redis or memcache

Source: Internet
Author: User
Tags php session

Session Introduction

Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the phone from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session. Sometimes we can see the words "during a browser session, ...", where the term "session" is used in its original meaning, refers to open from a browser window to close this period ①. The most confusing is the phrase "User (client) during a session", which may refer to a series of actions by a user (in the case of a series of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout, sometimes referred to as a transaction), However, sometimes it is possible to simply refer to a connection, or it may refer to the meaning of ①, where the difference can only be inferred by context ②.

However, when the term session is associated with a network protocol, it often implies a "connection-oriented" and/or "hold state" of the two meanings, "connection-oriented" refers to the communication between the two parties before communication to establish a channel of communication, such as telephone, until the other side of the phone communication to start, In contrast to writing letters, when you send out the letter you can not confirm the other person's address is correct, communication channels may not be able to establish, but for the sender, the communication has begun. "Hold state" means that the party of communication can associate a series of messages, so that the message can be interdependent, such as a waiter can recognize the return of the old customers and remember the last time the customer owed a money in the store. Examples of this type are "a TCP session" or "a POP3 session" ③.

In the era of the development of Web server, the semantics of the session in the context of web development has a new extension, which means a kind of solution ④ to maintain state between client and server. Sometimes the session is used to refer to the storage structure of this solution, such as "Keep XXX in Session" ⑤. Because the various languages used for Web development provide support for this solution to a certain extent, the session is also used to refer to the solution of the language in a particular language context, For example, the javax.servlet.http.HttpSession provided in Java is referred to as Session⑥.

Given that this confusion has not changed, the use of the term session in this article will be based on the context has different meanings, please pay attention to distinguish.
In this article, using the Chinese "browser session" to express the meaning of ①, using the "session mechanism" to express the meaning of ④, using "session" to express the meaning of ⑤, the use of specific "HttpSession" to express the meaning ⑥

Why do you want to save the session in the cache

As far as PHP is concerned, the session supported by the language itself is saved to the disk file in a file, saved in the specified folder, the saved path can be set in the configuration file or in the program using function Session_save_path (), but there is a disadvantage,

The first is to save to the file system, inefficient, as long as the usefulness of the session will be from a number of files to find the specified SessionID, inefficient.

The second is that when using more than one server may appear, the session lost problem (in fact, is saved on the other server).

Of course, saving in the cache can solve the above problem, if you use the PHP itself session function, you can use the Session_set_save_handler () function is convenient to the session of the processing process to re-control. If you do not use the PHP session series functions, you can write a similar session function, it is also possible, I am doing this project is this, will be based on the user's mid, login time to hash as sessionId, Each request must add SessionID to be considered legal (when the first login is not required, this time will create SessionID, return to the client), so it is very convenient, concise and efficient. Of course, this article is mainly about the PHP itself in the session "do the Dirty."

Session is saved in the cache

PHP to save the cache to Redis, you can use the configuration file, the session processing and save to make changes, of course, in the program using the Ini_set () function to modify also can, this is very convenient to test, I use this method here, of course, if the production environment is recommended to use the configuration file.

If you want to simply operate the session into Redis operation, you can run the code a bit.

<?phpini_set ("Session.save_handler", "Redis"), Ini_set ("Session.save_path", "tcp://localhost:6379"); session_ Start (); Header ("Content-type:text/html;charset=utf-8"); $_session[' view '] = ' zhangsan '; Echo $_session[' view ';

Here the Session.save_handler is set to Redis,session.save_path as the address and port of Redis, set to refresh later, and then look back at Redis, and you will find the SessionID generated in Redis, SessionID and browser requests are the same,

If it's memcache,

<?phpini_set ("Session.save_handler", "Memcache"), Ini_set ("Session.save_path", "tcp://localhost:11211"); Session_Start (); Header ("Content-type:text/html;charset=utf-8"); $_session[' view '] = ' zhangsan '; Echo $_session[' View '];

You can also use

Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destory ', ' GC ');

Use the following to customize a Redis_session class

<?phpclass redissession{Private $_redis = Array (' handler ' = NULL,//database connection handle ' host ' = null,    Redis port number ' port ' = null,);        Public function __construct ($array = Array ()) {isset ($array [' Host '])? $array [' Host ']: "false";        Isset ($array [' Port '])? $array [' Host ']: "false";    $this->_redis = Array_merge ($this->_redis, $array);            The public function begin () {//Set session handler function Session_set_save_handler (Array ($this, ' open '), Array ($this, ' close '), Array ($this, ' read '), array ($this, ' write '), Array ($this,    ' Destory '), Array ($this, ' GC '));        Public Function open () {$redis = new Redis ();        $redis->connect ($this->_redis[' host '), $this->_redis[' Port '];        if (! $redis) {return false;        } $this->_redis[' handler ' = $redis;        $this-&GT;GC (NULL);    return true; }//Off public functIon Close () {return $this->_redis[' handler ']->close ();    }//Read public function read ($session _id) {return $this->_redis[' handler ']->get ($session _id);  }//write Public function write ($sessionId, $sessionData) {return $this->_redis[' handler ']->set ($sessionId,    $sessionData); } Public Function Destory ($sessionId) {return $this->_redis[' handler ']->delete ($sessionId) >= 1? True    : false;        The Public Function GC () {//gets all SessionID, letting the expired release $this->_redis[' handler ']->keys ("*");    return true; }} $ses = new Redissession (' host ' = ' 127.0.0.1 ', ' port ' = ' 6379 '); $ses->begin (); Session_Start (); $_ session[' name ']= ' Zhangsan '; Echo $_session[' name '];

This allows you to implement session data, such as Redis code that must be installed during the execution of the apsaradb

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.