Home php教程 php手册 实现基于Memcache存储的Session类

实现基于Memcache存储的Session类

Jun 21, 2016 am 09:06 AM
memcache nbsp return session this

cache|session

我没事的时候写的自主实现Session功能的类,基于文件方式存储Session数据,测试基本通过,还比较好玩,实际应用没有意义,只不过是学习Session是如何实现的。

使用基于文件的Session存取瓶颈可能都是在磁盘IO操作上,所以对付小数据量的Session没有问题,但是如果碰到大数据量的Sesstion,那么可能无法胜任,现在利用Memcache来保存Session数据,直接通过内存的方式,效率自然能够提高不少,并且如果结合PHP的Memcache扩展,能够支持分布式的Memcache服务器,那么这个性能就能够提到更高,负载更多更复杂的应用。

说明:以下代码基于Memcache来保存Session数据,客户端必须安装有PHP的Memcache扩展,否则无法运行,同时本代码没有经过严格测试,只是作为学习代码。


//===========================================
// 程序:Memcache-Based Session Class
// 功能:基于Memcache存储的 Session 功能类
// 作者: heiyeluren
// 博客: http://blog.csdn.net/heiyeshuwu
// 时间: 2006-12-23
//===========================================


/**
 * 类名: FileSession Class
 * 功能: 自主实现基于Memcache存储的 Session 功能
 * 描述: 这个类就是实现Session的功能, 基本上是通过设置客户端的Cookie来保存SessionID,
 *         然后把用户的数据保存在服务器端,最后通过Cookie中的Session Id来确定一个数据是否是用户的,
 *         然后进行相应的数据操作, 目前的缺点是没有垃圾收集功能
 *
 *        本方式适合Memcache内存方式存储Session数据的方式,同时如果构建分布式的Memcache服务器,
 *        能够保存相当多缓存数据,并且适合用户量比较多并发比较大的情况
 * 注意: 本类必须要求PHP安装了Memcache扩展, 获取Memcache扩展请访问: 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;   
   
   
    /**
     * 构造函数
     *
     * @param bool $isInit - 是否实例化对象的时候启动Session
     */
    function MemcacheSession($isInit = false){
        if ($isInit){
            $this->start();
        }
    }

    //-------------------------
    //   外部方法
    //-------------------------
   
    /**
     * 启动Session操作
     *
     * @param int $expireTime - Session失效时间,缺省是0,当浏览器关闭的时候失效, 该值单位是秒
     */
    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);
        }       
    }
   
    /**
     * 判断某个Session变量是否注册
     *
     * @param string $varName -
     * @return bool 存在返回true, 不存在返回false
     */
    function is_registered($varName){
        if (!isset($_SESSION[$varName])){
            return false;
        }
        return true;
    }   
       
    /**
     * 注册一个Session变量
     *
     * @param string $varName - 需要注册成Session的变量名
     * @param mixed $varValue - 注册成Session变量的值
     * @return bool - 该变量名已经存在返回false, 注册成功返回true
     */
    function register($varName, $varValue){
        if (isset($_SESSION[$varName])){
            return false;
        }
        $_SESSION[$varName] = $varValue;
        $this->_saveSession();
        return true;
    }
   
    /**
     * 销毁一个已注册的Session变量
     *
     * @param string $varName - 需要销毁的Session变量名
     * @return bool 销毁成功返回true
     */
    function unregister($varName){
        unset($_SESSION[$varName]);
        $this->_saveSession();
        return true;
    }
   
    /**
     * 销毁所有已经注册的Session变量
     *
     * @return 销毁成功返回true
     */
    function destroy(){
        $_SESSION = array();
        $this->_saveSession();
        return true;   
    }
   
    /**
     * 获取一个已注册的Session变量值
     *
     * @param string $varName - Session变量的名称
     * @return mixed - 不存在的变量返回false, 存在变量返回变量值
     */
    function get($varName){
        if (!isset($_SESSION[$varName])){
            return false;
        }
        return $_SESSION[$varName];
    }   
   
    /**
     * 获取所有Session变量
     *
     * @return array - 返回所有已注册的Session变量值
     */
    function getAll(){
        return $_SESSION;
    }
   
    /**
     * 获取当前的Session ID
     *
     * @return string 获取的SessionID
     */
    function getSid(){
        return $this->sessId;
    }

    /**
     * 获取Memcache的配置信息
     *
     * @return array Memcache配置数组信息
     */
    function getMemConfig(){
        return $this->memConfig;
    }
   
    /**
     * 设置Memcache的配置信息
     *
     * @param string $host - Memcache服务器的IP
     * @param int $port - Memcache服务器的端口
     */
    function setMemConfig($host, $port){
        $this->memConfig = array('host'=>$host, 'port'=>$port);
    }   
   
   
    //-------------------------
    //   内部接口
    //-------------------------
   
    /**
     * 生成一个Session ID
     *
     * @return string 返回一个32位的Session ID
     */
    function _getId(){
        return md5(uniqid(microtime()));
    }
   
    /**
     * 获取一个保存在Memcache的Session Key
     *
     * @param string $sessId - 是否指定Session ID
     * @return string 获取到的Session Key
     */
    function _getSessKey($sessId = ''){
        $sessKey = ($sessId == '') ? $this->sessKeyPrefix.$this->sessId : $this->sessKeyPrefix.$sessId;
        return $sessKey;
    }   
    /**
     * 检查保存Session数据的路径是否存在
     *
     * @return bool 成功返回true
     */
    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;
        }
        $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;
    }
   
    /**
     * 获取Session文件中的数据
     *
     * @param string $sessId - 需要获取Session数据的SessionId
     * @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;
    }
   
    /**
     * 把当前的Session数据保存到Memcache
     *
     * @param string $sessId - Session ID
     * @return 成功返回true
     */
    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;
    }
   
    /**
     * 显示提示信息
     *
     * @param string $strMessage - 需要显示的信息内容
     * @param bool $isFailed - 是否是失败信息, 缺省是true
     */
    function _showMessage($strMessage, $isFailed = true){
        if ($isFailed){
            exit($strMessage);
        }
        echo $strMessage;
    }   
}
?>
 


 



Statement of this Website
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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution: Your organization requires you to change your PIN Solution: Your organization requires you to change your PIN Oct 04, 2023 pm 05:45 PM

The message "Your organization has asked you to change your PIN" will appear on the login screen. This happens when the PIN expiration limit is reached on a computer using organization-based account settings, where they have control over personal devices. However, if you set up Windows using a personal account, the error message should ideally not appear. Although this is not always the case. Most users who encounter errors report using their personal accounts. Why does my organization ask me to change my PIN on Windows 11? It's possible that your account is associated with an organization, and your primary approach should be to verify this. Contacting your domain administrator can help! Additionally, misconfigured local policy settings or incorrect registry keys can cause errors. Right now

How to adjust window border settings on Windows 11: Change color and size How to adjust window border settings on Windows 11: Change color and size Sep 22, 2023 am 11:37 AM

Windows 11 brings fresh and elegant design to the forefront; the modern interface allows you to personalize and change the finest details, such as window borders. In this guide, we'll discuss step-by-step instructions to help you create an environment that reflects your style in the Windows operating system. How to change window border settings? Press + to open the Settings app. WindowsI go to Personalization and click Color Settings. Color Change Window Borders Settings Window 11" Width="643" Height="500" > Find the Show accent color on title bar and window borders option, and toggle the switch next to it. To display accent colors on the Start menu and taskbar To display the theme color on the Start menu and taskbar, turn on Show theme on the Start menu and taskbar

Display scaling guide on Windows 11 Display scaling guide on Windows 11 Sep 19, 2023 pm 06:45 PM

We all have different preferences when it comes to display scaling on Windows 11. Some people like big icons, some like small icons. However, we all agree that having the right scaling is important. Poor font scaling or over-scaling of images can be a real productivity killer when working, so you need to know how to customize it to get the most out of your system's capabilities. Advantages of Custom Zoom: This is a useful feature for people who have difficulty reading text on the screen. It helps you see more on the screen at one time. You can create custom extension profiles that apply only to certain monitors and applications. Can help improve the performance of low-end hardware. It gives you more control over what's on your screen. How to use Windows 11

10 Ways to Adjust Brightness on Windows 11 10 Ways to Adjust Brightness on Windows 11 Dec 18, 2023 pm 02:21 PM

Screen brightness is an integral part of using modern computing devices, especially when you look at the screen for long periods of time. It helps you reduce eye strain, improve legibility, and view content easily and efficiently. However, depending on your settings, it can sometimes be difficult to manage brightness, especially on Windows 11 with the new UI changes. If you're having trouble adjusting brightness, here are all the ways to manage brightness on Windows 11. How to Change Brightness on Windows 11 [10 Ways Explained] Single monitor users can use the following methods to adjust brightness on Windows 11. This includes desktop systems using a single monitor as well as laptops. let's start. Method 1: Use the Action Center The Action Center is accessible

How to turn off private browsing authentication for iPhone in Safari? How to turn off private browsing authentication for iPhone in Safari? Nov 29, 2023 pm 11:21 PM

In iOS 17, Apple introduced several new privacy and security features to its mobile operating system, one of which is the ability to require two-step authentication for private browsing tabs in Safari. Here's how it works and how to turn it off. On an iPhone or iPad running iOS 17 or iPadOS 17, Apple's browser now requires Face ID/Touch ID authentication or a passcode if you have any Private Browsing tab open in Safari and then exit the session or app to access them again. In other words, if someone gets their hands on your iPhone or iPad while it's unlocked, they still won't be able to view your privacy without knowing your passcode

Win10/11 digital activation script MAS version 2.2 re-supports digital activation Win10/11 digital activation script MAS version 2.2 re-supports digital activation Oct 16, 2023 am 08:13 AM

The famous activation script MAS2.2 version supports digital activation again. The method originated from @asdcorp and the team. The MAS author calls it HWID2. Download gatherosstate.exe (not original, modified) from https://github.com/massgravel/Microsoft-Activation-Scripts, run it with parameters, and generate GenuineTicket.xml. First take a look at the original method: gatherosstate.exePfn=xxxxxxx;DownlevelGenuineState=1 and then compare with the latest method: gatheros

Detailed explanation of the usage of return in C language Detailed explanation of the usage of return in C language Oct 07, 2023 am 10:58 AM

The usage of return in C language is: 1. For functions whose return value type is void, you can use the return statement to end the execution of the function early; 2. For functions whose return value type is not void, the function of the return statement is to end the execution of the function. The result is returned to the caller; 3. End the execution of the function early. Inside the function, we can use the return statement to end the execution of the function early, even if the function does not return a value.

How to Hide and Unhide Folders on Windows 11 [3 Ways] How to Hide and Unhide Folders on Windows 11 [3 Ways] Sep 23, 2023 am 08:37 AM

Hiding folders is a great way to keep your desktop organized. Maybe you want to keep your personal files or some client details away from prying eyes. Whatever it is, the ability to put them away and unhide them when necessary is a big saver. In short, these hidden files will not show up in the main menu, but they will still be accessible. It's very simple and shouldn't take you too much time. How to hide a folder in Windows 11? 1. Use File Explorer and hit the + key to open File Explorer. WindowsE Find the folder you want to hide, right-click it and select Properties. Navigate to the General tab, check the Hide box, click Apply, and then click OK. In the next dialog box, check Apply changes to this folder, sub-folder

See all articles