Implements the session class based on Memcache storage.

Source: Internet
Author: User
Tags session id server port
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 based on Memcache storage Functional class//Author: heiyeluren//Blog: Http://blog.csdn.net/heiyeshuwu//Time: 2006-12-23//======================================= = = =/** * Class Name: Filesession class * Function: autonomous implementation based on Memcache storage session function * Description: This class is to implement the session function, basically by setting the client's cookies to save SES        Sionid, * then put the user's data on the server side, and finally through the cookie in the session ID to determine whether a data is a user, * 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, it can save quite a lot of cached data, and it is more suitable for the user to have more concurrency. * Note: This class must require PHP to install the MEMC
    Ache 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/function memcachesession ($isInit = fal when instantiating objects)
        SE) {if ($isInit) {$this->start ();
     }//-------------------------//External method//-------------------------/** * Start session operation
        * * @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); }/** * Determines whether a session variable is registered * * @param string $varName-* @return BOOL is returned TRU E, no return false/function is_registered ($varName) {if!isset ($_session[$varName])
        Alse;
    return true; /** * Register a Session variable * * @param string $varName-the variable name that needs to be registered as a session * @param mixed $v Arvalue-Register as the value of the session variable * @return BOOL-the variable name already exists returns false, the registration successfully returns TRUE */function register ($varName, $varVal
        UE) {if (Isset ($_session[$varName])) {return false;
        } $_session[$varName] = $varValue;
        $this->_savesession ();
    return true; /** * Destroy a registered Session variable * * @param string $varName-session variable name to be destroyed * @return bool destroy successfully return T
        Rue */function Unregister ($varName) {unset ($_session[$varName]);
        $this->_savesession ();
    return true; }/** * Destruction of thehave registered session variable * * @return Destroy successfully return True */function Destroy () {$_session = array ();
        $this->_savesession ();    
    return true; /** * Gets a registered session variable value * * @param string $varName-session variable name * @return Mixed-nonexistent variable 
        Returns FALSE, there is a variable return variable value */function Get ($varName) {if (!isset ($_session[$varName])) {returns false;
    return $_session[$varName];
        /** * Gets all session variables * * @return array-Returns all registered session variable values/function GetAll () {
    return $_session; /** * Gets the current session ID * * @return string SessionID/function GetSID () {RET
    Urn $this->sessid;
        /** * Get memcache configuration information * * @return array memcache configuration Array information * * Function Getmemconfig () {
    return $this->memconfig; /** * Set Memcache configuration information * * @param string $host-MEMCACHe server's IP * @param int $port-memcache Server port/function Setmemconfig ($host, $port) {$this->memco
    Nfig = Array (' Host ' => $host, ' Port ' => $port); }//-------------------------//internal interface//-------------------------/** * Generate a Sess Ion ID * * @return string returns a 32-bit session ID/function _getid () {return MD5 (uniqid microtime (
    ))); /** * Gets a session Key * * @param string $sessId saved in Memcache-Specifies the session ID * @return Stri Ng gets the session Key/function _getsesskey ($sessId = ') {$sessKey = ($sessId = = ")? $this-&GT;SESSKEYP
        Refix. $this->sessid: $this->sesskeyprefix. $sessId;
    return $sessKey;
        /** * Checks if the path that holds the session data exists * * @return BOOL successfully returns TRUE/function _initmemcacheobj () { if (!class_exists (' Memcache ') | | | |!function_exists (' memcache_connect ')) {$this->_showmessage (' FaileD:memcache extension not install, "from 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 (' Fai Led:connect memcache host '. $this->memconfig[' host ']. ': '.
        $this->memconfig[' Port ']. ' failed ');
        } $this->memobject = $mem;
    return true; 
     /** * Gets the data in the session file * * @param string $sessId-SessionID * @return to obtain session data 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;
     /** * Saves current session data to Memcache * * @param string $sessId-session ID * @return successfully returns True
        * * Function _savesession ($sessId = ') {$this->_initmemcacheobj ();
        $sessKey = $this->_getsesskey ($sessId); if (empty ($_session)) {$ret = @ $this->memobject->set ($sessKey, $_session, False, $this->sessexpiretim
        e);
        }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 a hint message * * @param string $strMessage-The information you need to display * @param bool $isFailed-whether it is a failure message, missing Province is true */function _showmessage ($strMessage, $isFailed = True) {if ($isFailed) {exit ($strMess
  Age);      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.