Multi-server sharing in-depth memcache session Data _php Tutorial

Source: Internet
Author: User
Tags session id
A related introduction
Introduction to multi-server data sharing with 1.memcache + memcache
, see http://www.guigui8.com/index.php/archives/206.html
2.session Mechanism:
The session mechanism is a server-side mechanism that uses a hash-like structure (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 SessionID, If a SessionID is already included, it indicates that the session was previously created for this client, and the server will follow SessionID to retrieve the session (if it is not retrieved, it may create a new one), if the client request does not contain SessionID, Creating a session for this client and generating a value for the Sessionid,sessionid associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern. This sessionid will be returned to the client in this response to save.

This sessionid can be saved in a cookie-like manner, so that the browser can automatically play the logo to the server during 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 it is under different primary domain, you can solve the problem through the central concept of the observer pattern, the solution that extends through this concept has a lot, and today I want to say, Is the previous one that simulates a session with Memcache's multi-server data sharing technology for multi-server sharing of current online user data.
For multi-server unified session information, the requirements are as follows:
1. Be able to save session information on several servers specified by memcached (memcache data sharing through the above described);
2. You can customize the value of session_id by session_id ($sessid), just before Session_Start (), as defined by Zend.
3. It is convenient to switch the session information stored in the memcached and the operation of the session information stored by the file when the system is running.

Three Codes
The implementation is very simple, through the memcache to simulate the session mechanism, just use memcache to replace the storage media with shared server memory, in order to achieve multiple distributed deployment of the server sharing session information purposes. And the interface of the call, and Zend provided by the session operation function is different, so it can be conveniently in the Memcache and file session information operation to build a switch.
The following code, has been tested several times, to achieve the above functional requirements. Paste the following first:
Copy CodeThe code is as follows:
/**
*=---------------------------------------------------------------------------=
* MemcacheSession.class.php
*=---------------------------------------------------------------------------=
*
* Implementation of Session function based on memcache storage
* (simulate session mechanism, just use memcache to swap storage media for shared server memory)
*
* Disadvantage: There is no implementation strategy to introduce the session sharing mechanism of different primary domains. That is, only the implementation under the same primary domain is supported.
*
* Copyright (c) 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 SessionID
* 2. Save the user's data on the server side, using the session ID in the cookie to determine if 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 '; Domain-wide 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 of Singleton objects
// }}}


/**
* A static method obtained by a singleton object.
* (server parameters that can provide memcache information storage by the way)
*
* @param string $host The server IP of the-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 function
*
* @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 operation
*
* @param int $expireTime-session failure time, 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 no need to be processed by cookie (so omit 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 exists returns TRUE, there is no return false
*/
Public function isregistered ($varName) {
if (!isset ($this->_sesscontainer[$varName])) {
return false;
}
return true;
}

/**
* Register a Session variable
*
* @param string $varName-variable name to register as session
* @param mixed $varValue-the value registered as a session variable
* @return BOOL-the variable name already exists returns false, registration succeeded returns true
*/
Public function set ($varName, $varValue) {
$this->_sesscontainer[$varName] = $varValue;
$this->_savesession ();
return true;
}

/**
* Gets the value of a registered session variable
*
* @param string $varName The name of the-session variable
* @return Mixed-the non-existent variable returns false, there is a variable return variable value
*/
Public function Get ($varName) {
if (!isset ($this->_sesscontainer[$varName])) {
return false;
}
return $this->_sesscontainer[$varName];
}

/**
* Destroys a registered session variable
*
* @param string $varName-Name of Session variable to be destroyed
* @return BOOL Destroy succeeded return True
*/
Public Function Delete ($varName) {
unset ($this->_sesscontainer[$varName]);
$this->_savesession ();
return true;
}

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


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

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

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

/**
* Set Memcache Server information
*
* @param string $host IP of the-memcache server
* @param int $port 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 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 of the configuration and cannot actually be removed from the memcached connection pool)
*
* @param string $host IP of the-memcache server
* @param int $port 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-whether to specify session ID
* @return String gets to the session Key
*/
Private Function _getsesskey ($_sessid = ") {
$sessKey = ($_sessid = = ")? $this->_sesskeyprefix. $this->_sessid: $this->_sesskeyprefix.$_sessid;
return $sessKey;
}
/**
* Check if the path to save session data exists
*
* @return BOOL Successfully returns true
*/
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 from the session file
*
* @param string $_sessid-SessionID to get 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 the current session data to Memcache
*
* @param string $_sessid-session ID
* @return Successful return True
*/
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 prompt information
*
* @param string $strMessage-the information content to be displayed
* @param bool $isFailed-is the 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, same as the original session operation, without any change. Such as:
Copy CodeThe code is as follows:
Session_Start ();
$_session[' file_session_info ']= ' local file Save SESSION information '; Session of local File save

session storage for 2.memcache shared servers
Copy CodeThe 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 feature is not available, the unique information passed according to the other parameters is set to map to session_id
if (1) {
$SN = ' 838ece1033bf7c7468e873e79ba2a3ec ';
$mem->setsessid ($SN);
}
$mem->set (' name ', ' Guigui '); Session with multiple Memcache servers shared
$mem->set (' addr ', ' Wuhan '); Session with multiple Memcache servers shared
$mem->destroy ();

3. Get session information for local and memcache storage, respectively
Copy CodeThe 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 ');

http://www.bkjia.com/PHPjc/327560.html www.bkjia.com true http://www.bkjia.com/PHPjc/327560.html techarticle For An introduction to multi-server data sharing for 1.memcache + memcache, see the http://www.guigui8.com/index.php/archives/206.html 2.session mechanism: Session mechanism is a service ...

  • 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.