In-depth memcache session data multi-server sharing detailed _php tips

Source: Internet
Author: User
Tags memcached mixed session id sessions server memory server port zend

A related introduction
1.memcache + memcache Introduction to multi-server data sharing
, see http://www.guigui8.com/index.php/ archives/206.html
2.session mechanism: the
session mechanism is a server-side mechanism that uses a structure similar to a hash table (or perhaps a hash table) to hold information.
When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID-called a SessionID, If you already have a sessionid that has previously created a session for this client, the server retrieves the session in accordance with SessionID (a new one may be created if it is not retrieved), if the client request does not contain SessionID, A session is created for this client and a value that generates a Sessionid,sessionid associated with this session should be a string that neither repeats nor is easily found to mimic. This sessionid will be returned to the client for saving in this response.

The way in which this sessionid can be saved is a cookie, so that the browser can automatically play the logo to the server in the interactive process.

Generally, the name of this cookie is similar to Seeesionid, and. For example, WebLogic for Web application-generated COOKIE,PHPSESSID=BYOK3VJFD75APNRF3K2HMDNV6QZCEBZWOWIBYENLERJ, its name is PHPSESSID.

Two motives
In the 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 a global cookie to handle the sharing of related data; If you are in a different primary domain, you can solve the problem through the central concept of the observer pattern, and there are many solutions that extend through this concept, and what I'm going to say today, Is the former, through the Memcache data sharing technology to simulate the session, for the current online user data sharing of multiple servers.
For multiple server unified session information, requirements are as follows:
1. Able to save session information on several servers specified in the memcached (through the Memcache data sharing described above);
2. Can customize session_id values before Session_Start (), as defined by Zend, by session_id ($SESSID).
3. Can conveniently in the system running, switch memcached stored session information and file stored session information operation.

Three code
The implementation is very simple, through the memcache to simulate the session mechanism, only the use of memcache storage medium to share the memory of the server, to achieve multiple distributed deployment of the server sharing session information purposes. The calling interface is different from the session operation function provided by Zend, so it is convenient to switch the session information operation of Memcache and file.
The following code, has been tested many times, to achieve the above functional requirements. Put it down first:

Copy Code code as follows:

/**
*=---------------------------------------------------------------------------=
* MemcacheSession.class.php
*=---------------------------------------------------------------------------=
*
* Implement the session functionality based on Memcache storage
* (simulate session mechanism, only use memcache to swap storage medium for shared server memory)
*
* Disadvantage: The implementation strategy of the session sharing mechanism of different primary domains is not introduced at the moment. That is, only the implementation under the same primary domain is supported.
*
* Copyright (c) 2008 by Guigui. All rights reserved.
* @author Guigui <evan_gui@163.com>
* @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. The user's data is stored on the server side, and the session ID in the cookie is used to determine whether a data is a user's
*/
Class Memcachesession
{
{{{} class member Property definition
public $memObject = null; Memcache Action Object Handle
Private $_sessid = ';
Private $_sesskeyprefix = ' sess_ ';
Private $_sessexpiretime = 86400;
Private $_cookiedomain = '. guigui8.com '; Full Domain 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 (); Session information for the current user
private static $_instance = null; This class is a single Instance object
// }}}


/**
* The static method obtained by a single instance object.
* (You can also provide memcache information storage server parameters)
*
* @param string $host server IP for-memcache data store
* @param integer $port the server port number of the-memcache data store
* @param BOOL $isInit-start session if object is instantiated
*/
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-start session if object is instantiated
*/
Private Function __construct ($host = ', $port =11211, $isInit = False) {
!empty ($host) && $this->_memservers = Array (Trim ($host) => $port);
$isInit && $this->start ();
}

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

/**
* Start Session action
*
* @param int $expireTime-session expiration time, the default is 0, 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;
Setcookie ($this->_cookiename, $this->_sessid, $this->_cookieexpiretime, "/", $this->_cookiedomain);
$this->_initmemcacheobj ();

$this->_sesscontainer = Array ();
$this->_savesession ();
} else {
$this->_sessid = $_sessid;
$this->_sesscontainer = $this->_getsession ($_SESSID);
}
}

/**
* Setsessid
*
* Custom session ID, usually not required to be processed by cookie (so omit the cookie record session_id)
*
* @param string $sess _id
* @return Boolean
*/
Public Function Setsessid ($sess _id) {
$_sessid = Trim ($sess _id);
if (!$_SESSID) {
return false;
} else {
$this->_sessid = $_sessid;
$this->_sesscontainer = $this->_getsession ($_SESSID);
}
}

/**
* Determine if a session variable is registered
*
* @param string $varName-
* @return BOOL Returns TRUE, does not exist returns false
*/
Public function isregistered ($varName) {
if (!isset ($this->_sesscontainer[$varName])) {
return false;
}
return true;
}

/**
* Register a Session variable
*
* @param string $varName-variable name that needs to be registered as a session
* @param mixed $varValue-values registered as session variables
* @return BOOL-the variable name already exists returns false, registration succeeds return 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-A variable that does not exist returns false and a variable returns a value
*/
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 destroyed successfully returns true
*/
Public Function Delete ($varName) {
unset ($this->_sesscontainer[$varName]);
$this->_savesession ();
return true;
}

/**
* Destroy all registered session variables
*
* @return Destroy successfully return True
*/
Public function Destroy () {
$this->_sesscontainer = Array ();
$this->_savesession ();
return true;
}


/**
* Get all Session Variables
*
* @return Array-Returns all registered session variable values
*/
Public Function GetAll () {
return $this->_sesscontainer;
}

/**
* Get the current session ID
*
* SessionID obtained by @return string
*/
Public Function GetSID () {
return $this->_sessid;
}

/**
* Get the Memcache server information
*
* @return Array memcache configuration information
*/
Public Function getmemservers () {
return $this->_memservers;
}

/**
* Set the Memcache server information
*
* @param string $host 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 the-memcache server
* @param int $port The port of the-memcache server
*/
Public Function Addmemserver ($host, $port) {
$this->_memservers[trim ($host)] = Trim ($port);
$this->memobject->addserver ($host, $port);
}

/**
* Remove Memcache Server (Note that this is just a removal configuration and cannot actually be removed from the memcached connection pool)
*
* @param string $host 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 Returns a 32-bit session ID
*/
Private Function _getid () {
return MD5 (Uniqid (Microtime ()));
}

/**
* Get a session Key saved in Memcache
*
* @param string $_sessid-Specify session ID
* @return String Gets the session Key
*/
Private Function _getsesskey ($_sessid = ') {
$sessKey = ($_sessid = = ")? $this->_sesskeyprefix. $this->_sessid: $this->_sesskeyprefix.$_sessid;
return $sessKey;
}
/**
* Check to see if the path that holds the session data exists
*
* @return BOOL Returns true successfully
*/
Private Function _initmemcacheobj () {
if (!class_exists (' Memcache ') | | |!function_exists (' memcache_connect ')) {
$this->_showmessage (' failed:memcache extension not install, in ' 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-SessionID to obtain 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 is $_cookie[' __sesshandler '] error!
return Array ();
}
return $sessData;
}

/**
* Save current session data to Memcache
*
* @param string $_sessid-session ID
* @return return True successfully
*/
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) {
$this->_showmessage (' Failed:save sessiont data Failed, please check memcache server ');
}
return true;
}

/**
* Display the prompt information
*
* @param string $strMessage-what information needs to be displayed
* @param bool $isFailed-whether it is a failure message, and the default is True
*/
Private Function _showmessage ($strMessage, $isFailed = True) {
Return
if ($isFailed) {
Echo ($strMessage);
}
Echo $strMessage;
}

Four Application
1. Local session storage, as in the original session operation, without any changes. Such as:
Copy Code code as follows:

Session_Start ();
$_session[' file_session_info ']= ' local file Save session information '; Session for local File save

2.memcache session storage for shared servers
Copy Code code 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 feature is not available, the setting is mapped to session_id based on the unique information passed by other parameters
if (1) {
$SN = ' 838ece1033bf7c7468e873e79ba2a3ec ';
$mem->setsessid ($SN);
}
$mem->set (' name ', ' Guigui '); Sessions shared by multiple memcache servers
$mem->set (' addr ', ' Wuhan '); Sessions shared by multiple memcache servers
$mem->destroy ();

3. Get local and Memcache stored session information separately
Copy Code code as follows:

$ADDR = $mem->get (' addr ');
$_mem_session= $mem->getall ();
echo "Var_dump ($_session);
echo "Var_dump ($_mem_session);
$res = $mem->delete (' name ');

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.