Directly on the code:
Copy CodeThe code is as follows:
Class Dbsession
{
Const TYPE_INT = 1;
Const TYPE_STR = 2;
/**
* Database configration
*
* @var Array
*/
Private $_config = Array (
' Host ' = ' 127.0.0.1′,
' Port ' = 3306,
' Username ' = ' root ',
' Password ' = ' root ',
' dbname ' = ' Db_mylab ',
' TableName ' = ' t_sessions ',
' Cookie_prefix ' = ' mylab_ ',
' Cookiepath ' = '/',
' Cookiedomain ' = ',
' Cookie_timeout ' = 900
);
/**
* Table Fields Type array
*
* @var Array
*/
Private $_db_fields = Array (
' Crc32sid ' = Self::type_int,
' Sessionhash ' = Self::type_str,
' Idhash ' = Self::type_str,
' UserID ' = Self::type_int,
' IPAddress ' = Self::type_str,
' LastActivity ' = Self::type_str,
' Location ' = Self::type_str,
' Loggedin ' = Self::type_int,
' Heartbeat ' = Self::type_str
);
/**
* DB obj
*
* @var Mysqli Object
*/
Private $_mysqli = null;
/**
* Weather The session was created or existed previously
*
* @var BOOL
*/
Private $_created = false;
/**
* Array of changes.
*
* @var Array
*/
Private $_changes = Array ();
/**
* @var BOOL
*/
Private $_db_inited = false;
/**
* Session Host
*
* @var String
*/
Private $_session_host = ";
/**
* Session Idhash
*
* @var String
*/
Private $_session_idhash = ";
Private $_dbsessionhash = ";
Private $_vars = Array ();
Public Function __construct ()
{
$this->_dbsessionhash = addslashes ($this->get_cookie (' Sessionhash '));
$this->_session_host = substr ($_server[' remote_addr '), 0, 15);
#This should *never* change during a session
$this->_session_idhash = MD5 ($_server[' http_user_agent '). Self::fetch_substr_ip (Self::fetch_alt_ip ()));
$this->_init_config ();
$this->init_db ();
$gotsession = false;
if ($this->_dbsessionhash)
{
$sql = '
SELECT *
From '. $this->_config[' tablename '). ‘
WHERE crc32sid = '. sprintf ('%u ', CRC32 ($this->_dbsessionhash)). ‘
and Sessionhash = ". $this->_dbsessionhash. ‘'
and Idhash = ". $this->_session_idhash. ‘'
and Heartbeat > '. Date (' y-m-d h:i:s ', timenow– $this->_config[' cookie_timeout '). ‘'‘;
echo $sql; exit;
$result = $this->_mysqli->query ($sql);
$session = $result->fetch_array (MYSQLI_ASSOC);
if ($session and ($this->fetch_substr_ip ($session [' ipaddress ']) = = $this->fetch_substr_ip ($this->_session_ Host)))
{
$gotsession = true;
$this->_vars = $session;
$this->_created = false;
}
}
if ($gotsession = = False)
{
$this->_vars = $this->fetch_session ();
$this->_created = true;
$gotsession = true;
}
if ($this->_created = = False)
{
$this->set (' lastactivity ', date (' y-m-d h:i:s ', TimeNow));
$this->set (' Location ', $_server[' Request_uri ');
}
}
/**
* Builds An array that can is used to build a query to insert/update the session
*
* @return array array of column name = prepared value
*/
Private Function _build_query_array ()
{
$return = Array ();
foreach ($this->_db_fields as $fieldname = $cleantype)
{
Switch ($cleantype)
{
Case Self::type_int:
$cleaned = Is_numeric ($this->_vars["$fieldname"])? $this->_vars["$fieldname"]: intval ($this->_vars["$fieldname"]);
Break
Case SELF::TYPE_STR:
Default
$cleaned = "'". Addslashes ($this->_vars["$fieldname"]). "'";
}
$return ["$fieldname"] = $cleaned;
}
return $return;
}
/**
* Sets a session variable and updates the change list.
*
* @param string Name of Session variable to update
* @param string Value to update the IT with
*/
Public function set ($key, $value)
{
if ($this->_vars["$key"]! = $value)
{
$this->_vars["$key"] = $value;
$this->_changes["$key"] = true;
}
}
Public function Get ($key)
{
return $this->_vars["$key"];
}
Public Function Unsetchangedvar ($var)
{
if (Isset ($this->_changes["$var"]))
{
unset ($this->_changes["$var"]);
}
}
/**
* Fetches a valid Sessionhash value, not necessarily the one tied to this session.
*
* @return String 32-character Sessionhash
*/
static function Fetch_sessionhash ()
{
return hash (' md5′, TimeNow. Rand (1, 100000). Uniqid ());
}
Private Function _init_config ()
{
$registry = Zend_registry::getinstance ();
$config = $registry->get (' config ');
$this->_config[' host '] = $config->database->params->host;
$this->_config[' port '] = $config->database->params->port;
$this->_config[' username ') = $config->database->params->username;
$this->_config[' password ') = $config->database->params->password;
$this->_config[' dbname ') = $config->database->params->dbname;
$this->_config[' tablename ') = $config->database->session->tablename;
}
/**
* Initialize database connection
*/
Public Function init_db ()
{
if ($this->_db_inited)
{
return true;
}
Mysqli_report (Mysqli_report_off);
$this->_mysqli = new Mysqli (
$this->_config[' host '),
$this->_config[' username '),
$this->_config[' password '),
$this->_config[' dbname '),
$this->_config[' Port ']
);
/* Check connection */
if (Mysqli_connect_errno ())
{
printf ("Connect failed:%sn", Mysqli_connect_error ());
Echo ' in ', __file__, ' on line ', __line__;
echo "{success:false, errors: {reason: ' Connect failed:". Addslashes (Mysqli_connect_error ()). "' }}";
Exit ();
}
$this->_mysqli->query (' Set names latin1′);
$this->_db_inited = true;
return true;
}
/**
* Fetches an alternate IP address of the "The current visitor", attempting to detect proxies etc.
*
* @return String
*/
static function Fetch_alt_ip ()
{
$alt _ip = $_server[' remote_addr ');
if (Isset ($_server[' http_client_ip '))
{
$alt _ip = $_server[' http_client_ip ');
}
else if (isset ($_server[' Http_from '))
{
$alt _ip = $_server[' Http_from ');
}
return $alt _ip;
}
/**
* Returns the IP address with the specified number of octets removed
*
* @param string IP Address
*
* @return String truncated IP address
*/
static function Fetch_substr_ip ($IP, $length = null)
{
Return implode ('. ', Array_slice (Explode ('. ', $ip), 0, 4– $length));
}
/**
* Fetches a default session. used when creating a new session.
*
* @param integer User ID The session should is for
*
* @return Array array of Session variables
*/
Public Function fetch_session ($userid = 0)
{
$sessionhash = Self::fetch_sessionhash ();
$this->set_cookie (' Sessionhash ', $sessionhash);
Return Array (
' Crc32sid ' = sprintf ('%u ', CRC32 ($sessionhash)),
' Sessionhash ' = $sessionhash,
' Idhash ' = $this->_session_idhash,
' UserID ' = $userid,
' IPAddress ' = $this->_session_host,
' LastActivity ' + date (' y-m-d h:i:s ', TimeNow),
' Location ' = $_server[' Request_uri ',
' Loggedin ' = $userid? 1:0,
' Heartbeat ' = Date (' y-m-d h:i:s ', TimeNow)
);
}
Public Function Get_cookie ($cookiename)
{
$full _cookiename = $this->_config[' Cookie_prefix '). $cookiename;
if (Isset ($_cookie[$full _cookiename]))
{
return $_cookie[$full _cookiename];
}
Else
{
return false;
}
}
Public Function Set_cookie ($name, $value = ", $permanent = 1, $allowsecure = True)
{
if ($permanent)
{
$expire = TimeNow + 60 * 60 * 24 * 365;
}
Else
{
$expire = 0;
}
if ($_server[' server_port ' = = = ' 443′)
{
We ' re using SSL
$secure = 1;
}
Else
{
$secure = 0;
}
Check for SSL
$secure = ((Req_protocol = = = ' https ' and $allowsecure)? true:false);
$name = $this->_config[' Cookie_prefix '). $name;
$filename = ' n/a ';
$linenum = 0;
if (!headers_sent ($filename, $linenum))
{//Consider showing an error message if there not sent using above variables?
if ($value = = "and strlen ($this->_config[' Cookiepath ') > 1 and strpos ($this->_config[' cookiepath '], '/')!== FA Lse
{
This would attempt to unset the cookie at each directory up the path.
ie, cookiepath =/test/abc/. These'll be unset:/,/test,/test/,/TEST/ABC,/test/abc/
This should hopefully prevent cookies conflicts when the cookie path is changed.
$dirarray = explode ('/', preg_replace (' #/+$# ', ", $this->_config[' Cookiepath ')));
$alldirs = ";
foreach ($dirarray as $thisdir)
{
$alldirs. = "$thisdir";
if (!empty ($thisdir))
{//try unsetting without the/at the end
Setcookie ($name, $value, $expire, $alldirs, $this->_config[' Cookiedomain '), $secure);
}
$alldirs. = "/";
Setcookie ($name, $value, $expire, $alldirs, $this->_config[' Cookiedomain '), $secure);
}
}
Else
{
Setcookie ($name, $value, $expire, $this->_config[' Cookiepath '), $this->_config[' Cookiedomain '], $secure);
}
}
else if (! DEBUG)
{
echo "Can ' t set cookies";
}
}
Private Function _save ()
{
$cleaned = $this->_build_query_array ();
if ($this->_created)
{
Var_dump ($cleaned);
# Insert Query
$this->_mysqli->query ('
INSERT IGNORE into '. $this->_config[' tablename '). ‘
('. Implode (', ', Array_keys ($cleaned)). ‘)
VALUES
('. Implode (', ', $cleaned). ‘)
‘);
}
Else
{
# Update Query
$update = Array ();
foreach ($cleaned as $key = $value)
{
if (!empty ($this->_changes["$key"]))
{
$update [] = "$key = $value";
}
}
if (sizeof ($update) > 0)
{
$sql = ' UPDATE '. $this->_config[' tablename '). ‘
SET '. Implode (', ', $update). ‘
WHERE crc32sid = '. sprintf ('%u ', CRC32 ($this->_dbsessionhash)). ‘
and Sessionhash = ". $this->_dbsessionhash. ‘'‘;
Echo $sql;
$this->_mysqli->query ($sql);
}
}
}
Public Function Getonlineusernum ()
{
$sql = '
SELECT Count (*) as CNT
From '. $this->_config[' tablename '). ‘
WHERE Loggedin = 1
and Heartbeat > '. Date (' y-m-d h:i:s ', timenow– $this->_config[' cookie_timeout '). ‘'‘;
$result = $this->_mysqli->query ($sql);
$row = $result->fetch_array (MYSQLI_ASSOC);
return $row [' CNT '];
}
Private Function _gc ()
{
$rand _num = rand (); # Randow integer between 0 and Getrandmax ()
if ($rand _num < 100)
{
$sql = ' DELETE from '. $this->_config[' tablename '). ‘
WHERE Heartbeat < '. Date (' y-m-d h:i:s ', timenow– $this->_config[' cookie_timeout '). ‘'‘;
$this->_mysqli->query ($sql);
}
}
Public Function __destruct ()
{
$this->_save ();
$this->_gc ();
$this->_mysqli->close ();
}
}
http://www.bkjia.com/PHPjc/781815.html www.bkjia.com true http://www.bkjia.com/PHPjc/781815.html techarticle directly on the code: Copy the code as follows: Class Dbsession {const TYPE_INT = 1; const TYPE_STR = 2;/** * Database configration * * @var Array */Private $_config = Array (' H ...