Implementing a session class based on Memcache storage

Source: Internet
Author: User
Tags array bool empty garbage collection connect session id variables variable
Cache|session

I'll be fine when I write the session function of the class, based on file storage session data, testing basic through, but also more fun, practical application is meaningless, but is learning how to achieve the session.

The use of file-based session access bottlenecks may be on disk IO operations, so there is no problem in dealing with small data volumes, but if you encounter a large amount of data sesstion, then you may not be able to do it, and now use Memcache to save sessions data, Directly through the memory of the way, the efficiency can naturally improve a lot, and if combined with PHP memcache extension, can support distributed Memcache Server, then this performance can be mentioned higher, more load more complex applications.

Description: The following code is based on Memcache to save session data, the client must be installed with PHP memcache extension, otherwise can not run, at the same time this code has not been strictly tested, just as learning code.


<?php
//===========================================
Program: memcache-based Session Class
Function: Session function class based on memcache storage
Author: Heiyeluren
Blog: Http://blog.csdn.net/heiyeshuwu
Time: 2006-12-23
//===========================================


/**
* Class Name: Filesession class
* Function: Implement the session function based on memcache storage independently
* Description: This class is the function of implementing the session, basically by setting the client's cookie to save the SessionID,
* Then save the user's data on the server side, and finally determine whether a data is user by using the session ID in the cookie.
* then the corresponding data operations, the current disadvantage is no garbage collection function
*
* This method is suitable for storing the session data in Memcache memory mode, and if the distributed Memcache Server is built,
* Able to save a considerable amount of cached data, and suitable for the number of users more concurrent relatively large situation
* Note: This class must require PHP to install memcache extensions, get Memcache extensions please visit: http://pecl.php.net
*/
Class Memcachesession
{
var $sessId = ';
var $sessKeyPrefix = ' Sess_ ';
var $sessExpireTime = 86400;
var $cookieName = ' __sesshandler ';
var $cookieExpireTime = ';
var $memConfig = array (' Host ' => ' 192.168.0.200 ', ' Port ' =>11211);
var $memObject = null;


/**
* Constructor
*
* @param BOOL $isInit-start session if object is instantiated
*/
function Memcachesession ($isInit = False) {
if ($isInit) {
$this->start ();
}
}

//-------------------------
External methods
//-------------------------

/**
* Start Session action
*
* @param int $expireTime-session expiration time, the default is 0, when the browser is closed, the value unit is seconds
*/
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->_initmemcacheobj ();
$_session = Array ();
$this->_savesession ();
} else {
$this->sessid = $sessId;
$_session = $this->_getsession ($sessId);
}
}

/**
* Determine if a session variable is registered
*
* @param string $varName-
* @return BOOL Returns TRUE, does not exist returns false
*/
function is_registered ($varName) {
if (!isset ($_session[$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
*/
function register ($varName, $varValue) {
if (Isset ($_session[$varName])) {
return false;
}
$_session[$varName] = $varValue;
$this->_savesession ();
return true;
}

/**
* 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
*/
function Unregister ($varName) {
Unset ($_session[$varName]);
$this->_savesession ();
return true;
}

/**
* Destroy all registered session variables
*
* @return Destroy successfully return True
*/
function Destroy () {
$_session = Array ();
$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
*/
function Get ($varName) {
if (!isset ($_session[$varName])) {
return false;
}
return $_session[$varName];
}

/**
* Get all Session Variables
*
* @return Array-Returns all registered session variable values
*/
function GetAll () {
return $_session;
}

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

/**
* Get configuration information for Memcache
*
* @return Array memcache configuration information
*/
function Getmemconfig () {
return $this->memconfig;
}

/**
* Set Memcache configuration information
*
* @param string $host IP of the-memcache server
* @param int $port The port of the-memcache server
*/
function Setmemconfig ($host, $port) {
$this->memconfig = Array (' Host ' => $host, ' Port ' => $port);
}


//-------------------------
Internal interface
//-------------------------

/**
* Generate a session ID
*
* @return String Returns a 32-bit session ID
*/
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
*/
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
*/
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;
}
$mem = new Memcache;
if (!@ $mem->connect ($this->memconfig[' host ', $this->memconfig[' Port ')) {
$this->_showmessage (' Failed:connect memcache host '. $this->memconfig[' host '. $this->memconfig[' Port ' ]. ' failed ');
}
$this->memobject = $mem;
return true;
}

/**
* Get the data in the session file
*
* @param string $sessId-SessionID to obtain session data
* @return Unknown
*/
function _getsession ($sessId = ' ") {
$this->_initmemcacheobj ();
$sessKey = $this->_getsesskey ($sessId);
$sessData = $this->memobject->get ($sessKey);
if (!is_array ($sessData) | | empty ($sessData)) {
$this->_showmessage (' failed:session ID '. $sessKey. ' Session data not exists ');
}
return $sessData;
}

/**
* Save current session data to Memcache
*
* @param string $sessId-session ID
* @return return True successfully
*/
function _savesession ($sessId = ' ") {
$this->_initmemcacheobj ();
$sessKey = $this->_getsesskey ($sessId);
if (empty ($_session)) {
$ret = @ $this->memobject->set ($sessKey, $_session, False, $this->sessexpiretime);
}else{
$ret = @ $this->memobject->replace ($sessKey, $_session, 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
*/
function _showmessage ($strMessage, $isFailed = True) {
if ($isFailed) {
Exit ($strMessage);
}
Echo $strMessage;
}
}
?>




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.