實現基於檔案儲存體的Session類

來源:互聯網
上載者:User

我沒事的時候寫的自主實現Session功能的類,基於檔案方式儲存Session資料,測試基本通過,還比較好玩,實際應用沒有意義,只不過是學習Session是如何?的。

一般基於檔案儲存體Session資料效率不是很高,畢竟跟磁碟IO是有關係的,如果需要多台伺服器共用資料,可以考慮使用NFS來儲存資料,如果需要比較快的速度,可以考慮使用共用記憶體(shm)來儲存資料,直接把Session資料存放區路徑指定為/dev/shm,這樣磁碟IO會提高不少,不過shm空間比較小,一般Linux下是60多M,所以不可能儲存太多資料。

<?php//=======================================// 程式:File-Based Session Class// 功能:基於檔案儲存體的 Session 功能類// 時間: 2006-12-22//=======================================/** * 類名: FileSession Class * 功能: 自主實現基於檔案儲存體的 Session 功能 * 描述: 這個類就是實現Session的功能, 基本上是通過設定用戶端的Cookie來儲存SessionID, *         然後把使用者的資料儲存在伺服器端,最後通過Cookie中的Session Id來確定一個資料是否是使用者的,  *         然後進行相應的資料操作, 目前的缺點是沒有垃圾收集功能 * *        本方式適合儲存在普通檔案、共用記憶體(SHM)、NFS伺服器等基於檔案儲存體的方式,推薦儲存在共用  *        記憶體當中,因為共用記憶體存取效率比較高,但是空間比較小,重啟後就銷毀了 */class FileSession{    var $sessId            = '';    var $sessSavePath     = '/tmp/';    var $isCreatePath     = true;    var $sessExpireTime = '';    var $sessFilePrefix = 'sess_';    var $cookieName     = '__SessHandler';        /**     * 建構函式     *     * @param bool $isInit - 是否執行個體化對象的時候啟動Session     */    function FileSession($isInit = false){        if ($isInit){            $this->start();        }    }    //-------------------------    //   外部方法    //-------------------------        /**     * 啟動Session操作     *     * @param int $expireTime - Session失效時間,預設是0,當瀏覽器關閉的時候失效, 該值單位是秒     */    function start($expireTime = 0){        $sessId = $_COOKIE[$this->cookieName];        if (!$sessId){            if (!$this->_checkSavePath()){                $this->_showMessage('Session save path '. $this->sessSavePath .' not or create path failed');            }            $this->sessId = $this->_getId();            $this->sessExpireTime = ($expireTime > 0) ? time() + $expireTime : 0;            setcookie($this->cookieName, $this->sessId, $this->sessExpireTime, "/", '');                        $_SESSION = array();            $this->_writeFile();        } else {            $this->sessId = $sessId;            $_SESSION = unserialize($this->_getFile($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->_writeFile();        return true;    }        /**     * 銷毀一個登入的Session變數     *     * @param string $varName - 需要銷毀的Session變數名     * @return bool 銷毀成功返回true     */    function unregister($varName){        unset($_SESSION[$varName]);        $this->_writeFile();        return true;    }        /**     * 銷毀所有已經註冊的Session變數     *     * @return 銷毀成功返回true     */    function destroy(){        $_SESSION = array();        $this->_writeFile();        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;    }    /**     * 擷取伺服器端儲存的Session資料的路徑     *     * @return string 儲存Session的路徑     */    function getSavePath(){        return $this->sessSavePath;    }        /**     * 設定儲存Session資料的路徑     *     * @param string $savePath - 需要儲存Session資料的絕對路徑     */    function setSavePath($savePath){        $this->sessSavePath = $savePath;    }                //-------------------------    //   內部介面    //-------------------------        /**     * 產生一個Session ID     *     * @return string 返回一個32位的Session ID     */    function _getId(){        return md5(uniqid(microtime()));    }        /**     * 檢查儲存Session資料的路徑是否存在     *     * @return bool 成功返回true     */    function _checkSavePath(){        if (file_exists($this->sessSavePath)){            return true;        }        if (!$this->isCreatePath){            return false;        }        if (!@mkdir($this->sessSavePath)){            $this->_showMessage('Failed: Session cache path '. $this->sessSavePath .'is not exists, create failed');        }        @chmod($this->sessSavePath, 0777);                return true;    }        /**     * 擷取Session檔案中的資料     *     * @param string $sessId - 需要擷取Session資料的SessionId     * @return unknown     */    function _getFile($sessId = ''){        $sessId = ($sessId == '') ? $this->sessId : $sessId;        $sessFile = $this->sessSavePath . $this->sessFilePrefix . $sessId;        if (!file_exists($sessFile)){            $this->_showMessage('Failed: Session file '. $sessFile .' not exists');        }        return file_get_contents($sessFile);    }        /**     * 把當前的Session資料寫入到資料檔案     *     * @param string $sessId - Session ID     * @return 成功返回true     */    function _writeFile($sessId = ''){        $sessId = ($sessId == '') ? $this->sessId : $sessId;        $sessFile = $this->sessSavePath . $this->sessFilePrefix . $sessId;        $sessStr = serialize($_SESSION);        if (!$fp = @fopen($sessFile, "w+")){            $this->_showMessage('Failed: Open session save file '. $sessFile .' failed');        }        if (!@fwrite($fp, $sessStr)){            $this->_showMessage('Failed: Write session data to '. $sessFile .' failed');        }        @fclose($fp);        return true;    }        /**     * 顯示提示資訊     *     * @param string $strMessage - 需要顯示的資訊內容     * @param bool $isFailed - 是否是失敗資訊, 預設是true     */    function _showMessage($strMessage, $isFailed = true){        if ($isFailed){            exit($strMessage);        }        echo $strMessage;    }    }?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.