search
HomeBackend DevelopmentPHP TutorialDetailed explanation of multi-server sharing of Session data in Memcache_PHP tutorial

Detailed explanation of multi-server sharing of Session data in Memcache_PHP tutorial

Jul 21, 2016 pm 03:07 PM
memcachesessiononeintroduceshareddataservergo deepofRelatedDetailed explanation

A related introduction
1. Introduction to multi-server data sharing of memcache + memcache
, please see http://www.guigui8.com/index.php/ archives/206.html
2.session mechanism:
The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to Save information.
When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier - called sessionid. If it already contains a sessionid, it means that this client has been used before. If the client has created a session, the server will retrieve the session and use it according to the sessionid (if it cannot be retrieved, it may create a new one). If the client request does not contain the sessionid, a session will be created for the client and a session will be generated related to the session. The associated sessionid. The value of sessionid should be a string that is neither repeated nor easy to find patterns to counterfeit. This sessionid will be returned to the client for storage in this response.

Cookie can be used to save this sessionid, so that during the interaction process, the browser can automatically display this identification to the server according to the rules.

Generally, the name of this cookie is similar to SEEESIONID. For example, for the cookie generated by weblogic, PHPSESSID=ByOK3vjFD75aPnrF3K2HmdnV6QZcEbzWoWiBYEnLerj, its name is PHPSESSID.

Second motivation
In an actual web production environment, an application system often distributes different business applications to different servers for processing.
When tracking current online user information, if it is the same primary domain name, you can use global cookies to handle the sharing of related data; if it is under different primary domains, you can solve the corresponding problem through the central concept of the observer mode. Problems, there are many solutions extended by this concept, and what I am going to talk about today is the former one, which uses memcache's multi-server data sharing technology to simulate sessions to share the current online user data with multiple servers.
Regarding the unified session information of multiple servers, the requirements are as follows:
1. Be able to save session information on several servers specified by memcached (through the memcache introduced earlier Multi-server data sharing);
2. You can customize the value of session_id through session_id ($sessid) before session_start() defined by zend.
3. It is easy to switch between session information stored in memcached and session information stored in files while the system is running.

Three codes
The implementation method is very simple. It uses memcache to simulate the session mechanism. It just uses memcache to replace the storage medium with the memory of a shared server to achieve multiple distribution The purpose of sharing session information among servers deployed in a formal manner. The calling interface is different from the session operation function provided by zend, so you can easily switch between memcache and file session information operations.
The following code has been tested many times and can meet the above functional requirements. Paste it below first:

Copy the code The code is as follows:

/**
*=------------------------------------------------ ----------------------------------=
*                                                                                                                                                                                                                                             -------------------------------------------------- --------------------=
*
* Implement the Session function based on Memcache storage
* (Simulate the session mechanism, just use memcache to store The medium is replaced by the memory of the shared server)
*
* Disadvantages: There is currently no implementation strategy for introducing the session sharing mechanism of different main domains. That is, only implementations in the same main domain are supported.
*
* Copyright(c) 2008 by guigui. All rights reserved.
* @author guigui
* @version $Id: MemcacheSession.class.php, v 1.0 2008/12/22 $
* @package systen
* @link http://www.guigui8.com
*/


/**
* class MemcacheSession
*
* 1. Set the client's cookie to save the SessionID
* 2. Save the user's data on the server side, and use the Session Id in the cookie to determine whether a data is User’s
*/
class MemcacheSession
{
// {{{ class members Property definition
public $memObject = null; //memcache operation object handle
private $_sessId = '';
private $_sessKeyPrefix = 'sess_';
private $_sessExpireTime = 86400;
private $_cookieDomain = '.guigui8.com'; //Global cookie domain name
private $_cookieName = '_PROJECT_MEMCACHE_SESS';
private $_cookieExpireTime = '';

private $_memServers = array(' 192.168.0.3' => 11211, '192.168.0.4' => 11211);
private $_sessContainer = array(); //Current user’s session information
private static $_instance = null; // Singleton object of this class
// }}}


/**
* Static method to obtain singleton object.
* (You can provide the server parameters for memcache information storage by the way)
*
* @param string $host - the server ip for memcache data storage
* @param integer $port - the server for memcache data storage Port number
* @param bool $isInit - Whether to start Session when instantiating the object
*/
public static function getInstance($host='', $port=11211, $isInit = true) {
if (null === self::$_instance) {
self::$_instance = new self($host, $port, $isInit);
}
return self::$ _instance;
}

/**
* Constructor
*
* @param bool $isInit - Whether to start Session when instantiating the object
*/
private function __construct($host='', $port=11211, $isInit = false){
!empty( $host) && $this->_memServers = array(trim($host) => $port);
$isInit && $this->start();
}

/**
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
 *      Public Methods
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
  */

/**
* Start Session operation
*
* @param int $expireTime - Session expiration time, the default is 0, it will expire when the browser is closed, the value unit is seconds
*/
public function start($expireTime = 0){
$_sessId = $_COOKIE[$this->_cookieName ];
if (!$_sessId){
$this->_sessId = $this->_getId();
$this->_cookieExpireTime = ($expireTime > 0) ? time () + $expireTime : 0;
                                                                                                                                                 this->_initMemcacheObj();

                   $this->_sessContainer = array(); $this-> ;_sessId = $_sessId;
                                                                                     🎜> public function setSessId($sess_id){
$_sessId = trim($sess_id);
if (!$_sessId){
return false;
} else {
$this- & gt; _Sessid = $ _Sessid;
$ This-& GT; _SessContainer = $ This-& GT; _getSession ($ _ SESSID);
public function isRegistered($varName){
if (!isset($this->_sessContainer[$varName])){
return false;
}
return true;
}   

   /**
* Register a Session variable
*
* @param string $varName - The name of the variable that needs to be registered as Session
* @param mixed $varValue - The value of the variable that needs to be registered as Session
* @ return bool - the variable name already exists and returns false, if the registration is successful, it returns true
*/
   public function set($varName, $varValue){
       $this->_sessContainer[$varName] = $varValue;
       $this->_saveSession();
       return true;
   }

   /**
* Get a registered Session variable value
*
* @param string $varName - the name of the Session variable
* @return mixed - returns false if the variable does not exist, returns the variable value if the variable exists
*/
   public function get($varName){
       if (!isset($this->_sessContainer[$varName])){
           return false;
       }
       return $this->_sessContainer[$varName];
   }   

   /**
* Destroy a registered Session variable
*
* @param string $varName - the name of the Session variable that needs to be destroyed
* @return bool If the destruction is successful, return true
*/
   public function delete($varName){
       unset($this->_sessContainer[$varName]);
       $this->_saveSession();
       return true;
   }

   /**
* Destroy all registered Session variables
*
* @return true if destroyed successfully
*/
   public function destroy(){
       $this->_sessContainer = array();
       $this->_saveSession();
       return true;   
   }

 
   /**
* Get all Session variables
*
* @return array - Return all registered Session variable values ​​
*/
   public function getAll(){
       return $this->_sessContainer;
   }

   /**
* Get the current Session ID
*
* @return string Get the SessionID
*/
   public function getSid(){
       return $this->_sessId;
   }

   /**
* Get Memcache server information
*
* @return array Memcache configuration array information
*/
   public function getMemServers(){
       return $this->_memServers;
   }

   /**
* Set the Memcache server information
*
* @param string $host - the IP of the Memcache server
* @param int $port - the port of the Memcache server
*/
   public function setMemServers($arr){
       $this->_memServers = $arr;
   }   

   /**
* Add Memcache server
*
* @param string $host - IP of Memcache server
* @param int $port - Port of Memcache server
*/
   public function addMemServer($host, $port){
       $this->_memServers[trim($host)] = trim($port);
       $this->memObject->addServer($host, $port);
   }  

   /**
* Remove the Memcache server (note that this only removes the configuration and cannot actually remove it from the memcached connection pool)
*
* @param string $host - the IP of the Memcache server
* @param int $port - the port of the Memcache server
*/
   public function removeMemServer($host){
  unset($this->_memServers[trim($host)]);
   }  

   /**
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
 *      Private Methods
  *=-----------------------------------------------------------------------=
  *=-----------------------------------------------------------------------=
  */

   /**
* Generate a Session ID
*
* @return string Return a 32-bit Session ID
*/
   private function _getId(){
       return md5(uniqid(microtime()));
   }

   /**
* Get a Session Key saved in Memcache
*
* @param string $_sessId - whether to specify the Session ID
* @return string Get the Session Key
*/
   private function _getSessKey($_sessId = ''){
       $sessKey = ($_sessId == '') ? $this->_sessKeyPrefix.$this->_sessId : $this->_sessKeyPrefix.$_sessId;
       return $sessKey;
   }   
   /**
* Check whether the path to save Session data exists
*
* @return bool Returns true if successful
*/
   private function _initMemcacheObj(){
       if (!class_exists('Memcache') || !function_exists('memcache_connect')){
           $this->_showMessage('Failed: Memcache extension not install, please from http://pecl.php.net download and install');
       }       
       if ($this->memObject && is_object($this->memObject)){
           return true;
       }
       $this->memObject = new Memcache;
       if (!empty($this->_memServers)) {
          foreach ($this->_memServers as $_host => $_port) {
            $this->memObject->addServer($_host, $_port);
        }
       }

       return true;
   }

   /**
* Get the data in the Session file
*
* @param string $_sessId - The SessionId that needs to get the Session data
* @return unknown
*/
   private function _getSession($_sessId = ''){
       $this->_initMemcacheObj();
       $sessKey = $this->_getSessKey($_sessId);
       $sessData = $this->memObject->get($sessKey);
       if (!is_array($sessData) || empty($sessData)){
         //this must be $_COOKIE['__SessHandler'] error!
         return array();
       }
       return $sessData;
   }

   /**
* Save the current Session data to Memcache
*
* @param string $_sessId - Session ID
* @return Return true on success
*/
   private function _saveSession($_sessId = ''){
       $this->_initMemcacheObj();
       $sessKey = $this->_getSessKey($_sessId);

       if (empty($this->_sessContainer)){
           $ret = @$this->memObject->set($sessKey, $this->_sessContainer, false, $this->_sessExpireTime);
       }else{
           $ret = @$this->memObject->replace($sessKey, $this->_sessContainer, false, $this->_sessExpireTime);
       }

if (!$ret){
_showMessage('Failed: Save sessiont data failed, please check memcache server');
}
return true;
}

/**
* Display prompt message
*
* @param string $strMessage - the message content to be displayed
* @param bool $isFailed - whether it is a failure message, the default is true
*/
private function _showMessage($strMessage, $isFailed = true){
return;
if ($isFailed){
echo ($strMessage);
}
echo $strMessage;
}

Four Applications
1 .Local session storage operates in the same manner as the original session, without any changes. For example:
Copy code The code is as follows:

session_start();
$_SESSION['file_session_info' ]= 'session information saved in local file'; //session saved in local file

2.memcache shared server's session storage
Copy code The code is as follows:

$mem= MemcacheSession::getInstance('192.168.0.4', 11211);
$mem->addMemServer( '192.168.0.4',11211);
$mem->addMemServer('192.168.0.5',11211);
//If the cookie function is not available, set the mapping based on the unique information passed by other parameters for session_id
if(1) {
$sn= '838ece1033bf7c7468e873e79ba2a3ec';
$mem->setSessId($sn);
}
$mem->set('name ','guigui'); //session shared by multiple memcache servers
$mem->set('addr','wuhan'); //session shared by multiple memcache servers
//$ mem->destroy();

3. Get the session information stored locally and in memcache respectively
Copy code The code is as follows:

$addr= $mem->get('addr');
$_MEM_SESSION= $mem->getAll();
echo "
localhost file session:";
var_dump($_SESSION);
echo"
memcache session:";
var_dump($_MEM_SESSION);
//$res = $mem->delete('name');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327560.htmlTechArticleA related introduction 1. For an introduction to multi-server data sharing of memcache + memcache, please see http://www. guigui8.com/index.php/archives/206.html 2.session mechanism: The session mechanism is a service...
Statement
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
Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

Explain Fibers in PHP 8.1 for concurrency.Explain Fibers in PHP 8.1 for concurrency.Apr 12, 2025 am 12:05 AM

Fibers was introduced in PHP8.1, improving concurrent processing capabilities. 1) Fibers is a lightweight concurrency model similar to coroutines. 2) They allow developers to manually control the execution flow of tasks and are suitable for handling I/O-intensive tasks. 3) Using Fibers can write more efficient and responsive code.

The PHP Community: Resources, Support, and DevelopmentThe PHP Community: Resources, Support, and DevelopmentApr 12, 2025 am 12:04 AM

The PHP community provides rich resources and support to help developers grow. 1) Resources include official documentation, tutorials, blogs and open source projects such as Laravel and Symfony. 2) Support can be obtained through StackOverflow, Reddit and Slack channels. 3) Development trends can be learned by following RFC. 4) Integration into the community can be achieved through active participation, contribution to code and learning sharing.

PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function