PHP independent Session database storage operation class sharing _ php instance

Source: Internet
Author: User
Tags crc32
This article mainly introduces the PHP independent Session database storage operation class sharing. If you need it, refer to the following code:

The Code is as follows:


Class DbSession
{

Const TYPE_INT = 1;
Const TYPE_STR = 2;

/**
* Database configration
*
* @ Var array
*/
Private $ _ config = array (
'Host' => '2017. 0.0.1 ′,
'Port' => 3306,
'Username' => 'root ',
'Password' => 'root ',
'Dbname' => 'db _ mylab ',
'Tablename' => 't_ session ',
'Cookie _ prefix' => 'mylab _',
'Cookiepath' => '/',
'Cookiedomain' => ",
'Cookie _ timeout' = & gt; 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 previusly
*
* @ 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 shoshould * 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 be 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 it
*/
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 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 shoshould be
*
* @ 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'] = '000000 ′)
{
// 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'/';
$ 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'], '/')! = False)
{
// This will attempt to unset the cookie at each directory up the path.
// Ie, cookiepath =/test/abc/. These will be unset:/,/test,/test/,/test/abc,/test/abc/
// This shoshould hopefully prevent cookie 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 ();
}

}

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.