An article deep you to understand cookies and sessions, with the distributed Web System Redis shared session scheme

Source: Internet
Author: User
Tags php language session id setcookie redis server

What is the difference between a cookie and a session? This is a very basic point of knowledge, everyone may know a general: The cookie is present on the client, the session is stored on the server, the cookie and session is used to verify the user's login status, Common Application scenarios: User login, user shopping cart data. Occasionally encountered in the development of these basic knowledge, but also to Baidu, today do a complete record, easy to consult later.

1. Basic Concepts

Cookies are stored on client computers in general: C:\users\***\appdata\local\microsoft\windows\temporary Internet Files (folders are hidden), You can go to your computer's IE settings to view, directly open.

Let's create a simple file test that sets a cookie and session:

<?php$value = "My cookie value";//Send a simple Cookiesetcookie ("TestCookie", $value, Time () +3600, "/", "127.0.0.1");// Setcookie ("TestCookie", $value, Time () +3600*24); echo "Setcookie success!<br/>"; session_start ();// Views count existing SESSION inside if (isset ($_session[' views ')))  $_session[' views ']=$_session[' views ']+1;else  $_session [' Views ']=1;echo ' views= '. $_session[' views ']. " <br/> "; Echo session_id ()." <br/> ";p rint_r ($_session); echo" Setsession success! ";? >

Under Access, use the debugging tools to see the cookie:

OK, you can see the settings cookie is successful, and the server also generated a corresponding session, server storage session location is generally found in php.ini:

Find the corresponding directory can be seen: Session file in sess_*********************** format storage, according to the above PHPSESSID can correspond to the session file is: open to see, Compare it to the session we promised:

Obviously, the content here is the content in $_session. The entire interactive process of the cookie and session is represented by a graph:

Or, in a little more detail:

In daily high concurrency, distributed systems often encounter a problem, high concurrent requests on the server load pressure is too large, and then our plan is to do load balancing, using Nginx to do reverse proxy, multiple hosts (tomcat or Apache) to do back-end response. Here, the problem comes, multiple servers, different requests distributed to different servers, generated a different session, if it is stored in memory or file, then can not maintain the same user login status, how can we solve it?

Here to choose according to the actual situation of our system:

A. If it is not high concurrency, the user is very few, the session is not very frequent, we can choose to store the session in the MySQL database

B. If there is a certain demand for performance, and the operation is frequent, we can choose k/v unstructured database, such as: Redis

If you use the PHP language, both of the above scenarios need to be modified in php.ini = files in Session.save_handler = files changed to user

For installation of Redis installations and Php-redis extensions Click here: Windows Redis and Php-redis installation

Here we give a PHP reference code: PHP has a session_set_save_handler () function, you can customize the operation of the session, the main operations, open, write, read, delete the corresponding to the function of the 6 parameters.bool session_set_save_handler  (  callable  $open  , < Span class= "Methodparam" >callable  $close  , < Span class= "Methodparam" >callable  $read  , < Span class= "Methodparam" >callable  $write  , < Span class= "Methodparam" >callable  $destroy ,  callable  $GC < Span class= "type"),

session_set_save_handlerfunction each parameter function as follows table

Parameters Description
Open This function is called when the session is opened. Receive two parameters, the first parameter is to maintain the path of the session, the second parameter is the name of the session
Close This function is called when the session operation is complete. No parameters are received.
Read The session ID is used as the parameter. The data is obtained from the data store by the session ID, and this data is returned. If the data is empty, you can return an empty string. This function session_start is triggered before the call
Write Called when the data is stored. There are two parameters, one is the session ID, the other is the session data
Destroy The session_destroy destroy function is triggered when the function is called. Only one parameter session ID
Gc Triggered when PHP executes the session garbage collection mechanism

< Span class= "Methodparam" > < Span class= "type" >< Span class= "Methodparam" >

< Span class= "Methodparam" > < Span class= "type" >< Span class= "Methodparam" >session Management action class: sessionredismanage.php

<?phpclass sessionredismanage {private $redis;    Private $sessionSavePath;    Private $sessionName;    Private $sessionExpireTime = 1800;    The duration of the session is set to 1800 seconds/** * Constructor/Public function __construct () {$this->redis = new Redis (); Create a Redis Client object $this->redis->connect (' 127.0.0.1 ', 6379) | | Die (' Connect to Redis server failed!     ‘);    Connect Redis server $this->redis->auth (' foobared ');        Password Authentication $this->redis->select (0); Select database Number No. 0 $retval = Session_set_save_handler (Array ($this, "open"), Array ($this, "C Lose "), Array ($this," read "), Array ($this," write "), Array ($this," destroy        "), Array ($this," GC "));    Session_Start ();    Start session} Public function open ($patn, $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;        } else {return false;        }} Public Function Destory ($id) {if ($this->redis->delete ($id)) {return true;        } else {return false;    }} Public Function GC ($MAXLIFETIME) {return true;    } public Function __destruct () {session_write_close (); }}?>

Note: In the Write method in the above code, with SessionID as the key name, the value of session is stored in Redis as value, and in the Read method, SessionID is used as the key name, and the value from Redis is returned. In the destroy callback function, the corresponding session data is removed from the Redis server with SessionID as key.

Then, new session_set.php and session_get.php to set, get the session value, we test it.

session_set.php

<?phprequire ' sessionmanager.php '; new SessionManager ();    Instantiate the object, open the custom SESSION storage mechanism $_session[' username ' = ' masonzhang ';     Write Sessionecho "Session_set success!";? >

session_get.php

<?phprequire ' sessionmanager.php '; new SessionManager ();    Instantiate the object and open the custom SESSION storage mechanism echo $_session[' username '];     Gets the specified session variable?>

Test: Access session_set.php first

Take a look at the Redis database:

Then visit session_get.php

After testing, different tabs can be obtained to username, which means that they can be accessed across pages.

< Span class= "Methodparam" > < Span class= "type" >< Span class= "Methodparam" > Here we can implement Nginx+php+redis session sharing.

< Span class= "Methodparam" > < Span class= "type" >< Span class= "Methodparam" >  share a Java version, we learn together:

http://blog.csdn.net/xlgen157387/article/details/52024139

An article deep you to understand cookies and sessions, with the distributed Web System Redis shared session scheme

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.