Implementation code _php instance of session adding Redis

Source: Internet
Author: User
Tags php session redis sessions

Session information into Redis

Session Introduction

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

In this article, use the Chinese "browser session" to express the meaning of ①, use the "sessional mechanism" to express the meaning of ④, use "sessions" to express the meaning of ⑤, use the specific "HttpSession" to express the meaning ⑥

Why should I save the session in the cache

In the case of PHP, the session supported by the language itself is saved in a file to a disk file, saved in a specified folder, the saved path can be set in a configuration file or used in a program using the function Session_save_path (), but there are drawbacks to doing so.
The first is to save to the file system, inefficient, as long as useful to the session will be from many files to find the specified SessionID, inefficient.
The second is that when you use more than one server, there may be a session loss problem (which is actually saved on a different server).
Of course, saving in the cache can solve the above problem, if you use the session function of PHP itself, you can use the Session_set_save_handler () function is very convenient to the session of the process of control. If you do not use the PHP session series function, you can write a similar session function, it is also possible, I now do this project is this, according to the user's mid, login time for hash as sessionId, Each request must be added SessionID to be legal (the first time is not required to login, this time will create SessionID, return to the client), this is also very convenient, simple and efficient. Of course, this article is mainly about the PHP itself in the session "to do tricks."

Session saved in cache

PHP saves the cache to Redis. You can use the configuration file, the session processing and save to make changes, of course, in the program to use 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 or recommend the use of configuration files.

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

<?php ini_set ("Session.save_handler", "Redis"); 
 
Ini_set ("Session.save_path", "tcp://localhost:6379"); 
 
Session_Start (); 
 
Header ("Content-type:text/html;charset=utf-8"); 
 
if (Isset ($_session[' view ')) {$_session[' view '] = $_session[' view '] + 1; 
 
}else{$_session[' view ' = 1; 
 
echo "View" {$_session[' view ']} "; Here set the Session.save_handler mode to Redis,session.save_path for the Redis address and port, set after the refresh, and then look back to see Redis, will find Redis in the generation of SessionID, 
 
SessionID and browsers request the same,//can also use Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destory ', ' GC '); Use the following to customize a Redis_session class <?php classes 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, ' dest 
 
  Ory '), Array ($this, ' GC ')); 
 
    The 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; 
 
  //The Public function closed () {return $this->_redis[' handler ']->close (); 
 
  //Read Public function reads ($session _id) {return $this->_redis[' handler ']->get ($session _id); //Writes Public function write ($sessionId, $sessionData) {return $this->_redis[' handler ']->set ($sessio 
 
  NId, $sessionData); 
Public Function Destory ($sessionId) { 
    Return $this->_redis[' handler ']->delete ($sessionId) >= 1? 
 
  True:false; 
 
    The Public Function GC () {//Get all SessionID, let the expired release $this->_redis[' handler ']->keys ("*"); 
 
  return true; 
 
} $ses = new Redissession (Array (' 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 execution, which must be installed Redis.

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.