Implementing a session class based on file storage

Source: Internet
Author: User
Tags array bool garbage collection mixed session id variables save file
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.

Generally based on file storage session data efficiency is not very high, after all, with disk IO is related to, if you need more than one server to share data, you can consider using NFS to store data, if you need faster speed, you can consider using shared memory (SHM) to save data, The session data storage path directly designated as/DEV/SHM, so disk IO will improve a lot, but SHM space is relatively small, general Linux is more than 60 m, so it is impossible to save too much data.

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


/**
* Class Name: Filesession class
* Function: Self-implementation of the session function based on file storage
* 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 storage in common file, shared memory (SHM), NFS server and so on, and is recommended to be saved in the shared
* Memory, because the shared memory access efficiency is high, but the space is relatively small, reboot after the destruction of
*/
Class Filesession
{
var $sessId = ';
var $sessSavePath = '/tmp/';
var $isCreatePath = true;
var $sessExpireTime = ';
var $sessFilePrefix = ' Sess_ ';
var $cookieName = ' __sesshandler ';

/**
* Constructor
*
* @param BOOL $isInit-start session if object is instantiated
*/
function Filesession ($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) {
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));
}
}

/**
* 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->_writefile ();
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->_writefile ();
return true;
}

/**
* Destroy all registered session variables
*
* @return Destroy successfully return True
*/
function Destroy () {
$_session = Array ();
$this->_writefile ();
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 the path of the server-side saved session data
*
* @return String to save the path to the session
*/
function Getsavepath () {
return $this->sesssavepath;
}

/**
* Set the path to save session data
*
* @param string $savePath-Absolute path to save session data
*/
function Setsavepath ($savePath) {
$this->sesssavepath = $savePath;
}


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

/**
* Generate a session ID
*
* @return String Returns a 32-bit session ID
*/
function _getid () {
return MD5 (Uniqid (Microtime ()));
}

/**
* Check to see if the path that holds the session data exists
*
* @return BOOL Returns true successfully
*/
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;
}

/**
* Get the data in the session file
*
* @param string $sessId-SessionID to obtain session data
* @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);
}

/**
* Write the current session data to the data file
*
* @param string $sessId-session ID
* @return return True successfully
*/
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;
}

/**
* 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.