Make Your Sessions More Secure
- astkboy2008
- Born


- Joined: Dec 29, 2009
- Posts: 3
- Status: Offline
Storing session data in a MySQL required a php class. This class implements a new PHP session handler that can replace the default PHP session handler by storing session data in a MySQL database table.
The session handler works just by creating an object of this class. After that, applications just need to use the same code to store and retrieve session variables. How can I use it? It's very easy - just see this example:
and the session will store in the mysql after that
The session handler works just by creating an object of this class. After that, applications just need to use the same code to store and retrieve session variables. How can I use it? It's very easy - just see this example:
Code: [ Select ]
<?php
// first create the required mySQL table that is used by this class
// you can do that by running in mySQL the "session_data.sql" file
// from the "install" folder!
// change the next values to match the setting of your mySQL database
$mySQLHost = "localhost";
$mySQLUsername = "username";
$mySQLPassword = "password";
// this is the name of the database where you created the table
// used by this class
$mySQLDatabase = "database";
$link = mysql_connect($mySQLHost, $mySQLUsername, $mySQLPassword);
if (!$link) {
die ("Could not connect to database!");
}
$db = mysql_select_db($mySQLDatabase, $link);
if (!$db) {
die ("Could not select database!");
}
// include the session manager class
require "../class.dbsession.php";
// instantiate a new session object
// note that you don't need to call the session_start() function
// as it is called automatically when the object is instantiated
$session = new dbsession();
// from now on, use sessions as you would normally
// the only difference is that session data is no longer saved on the server
// but in your database, making the data in it more secure
print_r("
The first time you run the script there should be an empty array (as there's nothing in the
\$_SESSION array)<br />
After you press \"refresh\" on your browser you will se the values that were
written in the \$_SESSION array<br>
");
print_r("<pre>");
print_r($_SESSION);
print_r("</pre>");
// add some values to the session
$_SESSION["value1"] = "hello";
$_SESSION["value2"] = "world";
// now check the table and see that there is data in it!
// to completely delete a session uncomment the following line
//$session->stop();
?>
// first create the required mySQL table that is used by this class
// you can do that by running in mySQL the "session_data.sql" file
// from the "install" folder!
// change the next values to match the setting of your mySQL database
$mySQLHost = "localhost";
$mySQLUsername = "username";
$mySQLPassword = "password";
// this is the name of the database where you created the table
// used by this class
$mySQLDatabase = "database";
$link = mysql_connect($mySQLHost, $mySQLUsername, $mySQLPassword);
if (!$link) {
die ("Could not connect to database!");
}
$db = mysql_select_db($mySQLDatabase, $link);
if (!$db) {
die ("Could not select database!");
}
// include the session manager class
require "../class.dbsession.php";
// instantiate a new session object
// note that you don't need to call the session_start() function
// as it is called automatically when the object is instantiated
$session = new dbsession();
// from now on, use sessions as you would normally
// the only difference is that session data is no longer saved on the server
// but in your database, making the data in it more secure
print_r("
The first time you run the script there should be an empty array (as there's nothing in the
\$_SESSION array)<br />
After you press \"refresh\" on your browser you will se the values that were
written in the \$_SESSION array<br>
");
print_r("<pre>");
print_r($_SESSION);
print_r("</pre>");
// add some values to the session
$_SESSION["value1"] = "hello";
$_SESSION["value2"] = "world";
// now check the table and see that there is data in it!
// to completely delete a session uncomment the following line
//$session->stop();
?>
- <?php
- // first create the required mySQL table that is used by this class
- // you can do that by running in mySQL the "session_data.sql" file
- // from the "install" folder!
- // change the next values to match the setting of your mySQL database
- $mySQLHost = "localhost";
- $mySQLUsername = "username";
- $mySQLPassword = "password";
- // this is the name of the database where you created the table
- // used by this class
- $mySQLDatabase = "database";
- $link = mysql_connect($mySQLHost, $mySQLUsername, $mySQLPassword);
- if (!$link) {
- die ("Could not connect to database!");
- }
- $db = mysql_select_db($mySQLDatabase, $link);
- if (!$db) {
- die ("Could not select database!");
- }
- // include the session manager class
- require "../class.dbsession.php";
- // instantiate a new session object
- // note that you don't need to call the session_start() function
- // as it is called automatically when the object is instantiated
- $session = new dbsession();
- // from now on, use sessions as you would normally
- // the only difference is that session data is no longer saved on the server
- // but in your database, making the data in it more secure
- print_r("
- The first time you run the script there should be an empty array (as there's nothing in the
- \$_SESSION array)<br />
- After you press \"refresh\" on your browser you will se the values that were
- written in the \$_SESSION array<br>
- ");
- print_r("<pre>");
- print_r($_SESSION);
- print_r("</pre>");
- // add some values to the session
- $_SESSION["value1"] = "hello";
- $_SESSION["value2"] = "world";
- // now check the table and see that there is data in it!
- // to completely delete a session uncomment the following line
- //$session->stop();
- ?>
and the session will store in the mysql after that
- Anonymous
- Bot


- Joined: 25 Feb 2008
- Posts: ?
- Loc: Ozzuland
- Status: Online
January 6th, 2010, 5:48 am
- UPSGuy
- Lurker ಠ_ಠ


- Joined: Jul 25, 2005
- Posts: 2735
- Loc: Nashville, TN
- Status: Offline
I've edited your post for organization and meaningful content. If you would like to continue your example and share the required class code here as well, I am ok with that, but please do not post threads only to redirect to your personal page. We're about learning here - not marketing.
The required file, class.dbsession.php:
The required file, class.dbsession.php:
Code: [ Select ]
<?php
/**
* A class to handle sessions by using a mySQL database for session related data storage providing
better
* security then the default session handler used by PHP.
*
* To prevent session hijacking, don't forget to use the {@link regenerate_id} method whenever you
do a
* privilege change in your application
*
* <i>Before usage, make sure you use the session_data.sql file from the
<b>install</b> folder to set up the table
* used by the class</i>
*
* After instantiating the class, use sessions as you would normally
*
* This class is an adaptation of John Herren's code from the "Trick out your session
handler" article
* ({@link http://devzone.zend.com/node/view/id/141}) and Chris Shiflett's code from Chapter 8,
Shared Hosting - Pg 78-80,
* of his book - "Essential PHP Security" ({@link http://phpsecurity.org/code/ch08-2})
*
* <i>Note that the class assumes that there is an active connection to a mySQL database and
it does not attempt to create
* one. This is due to the fact that, usually, there is a config file that holds the database
connection related
* information and another class, or function that handles database connection. If this is not how
you do it, you can
* easily adapt the code by putting the database connection related code in the "open"
method of the class.</i>
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5
License.
* To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/}
or send a letter to
* Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* For more resources visit {@link http://stefangabos.blogspot.com}
*
* @author Stefan Gabos <ix@nivelzero.ro>
* @version 1.0.1 (last revision: August 11, 2006)
* @copyright (c) 2006 Stefan Gabos
* @package dbSession
*/
error_reporting(E_ALL);
class dbSession
{
/**
* Constructor of class
*
* Initializes the class and starts a new session
*
* There is no need to call start_session() after instantiating this class
*
* @param integer $gc_maxlifetime the number of seconds after which data will be seen
as 'garbage' and
* cleaned up on the next run of the gc (garbage
collection) routine
*
* Default is specified in php.ini file
*
* @param integer $gc_probability used in conjunction with gc_divisor, is used to
manage probability that
* the gc routine is started. the probability is
expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100
means that there is
* a 1% chance the the gc routine will be called on
each request
*
* Default is specified in php.ini file
*
* @param integer $gc_divisor used in conjunction with gc_probability, is used to
manage probability
* that the gc routine is started. the probability is
expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100
means that there is
* a 1% chance the the gc routine will be called on
each request
*
* Default is specified in php.ini file
*
* @return void
*/
function dbSession($gc_maxlifetime = "", $gc_probability = "", $gc_divisor =
"")
{
// if $gc_maxlifetime is specified and is an integer number
if ($gc_maxlifetime != "" && is_integer($gc_maxlifetime)) {
// set the new value
@ini_set('session.gc_maxlifetime', $gc_maxlifetime);
}
// if $gc_probability is specified and is an integer number
if ($gc_probability != "" && is_integer($gc_probability)) {
// set the new value
@ini_set('session.gc_probability', $gc_probability);
}
// if $gc_divisor is specified and is an integer number
if ($gc_divisor != "" && is_integer($gc_divisor)) {
// set the new value
@ini_set('session.gc_divisor', $gc_divisor);
}
// get session lifetime
$this->sessionLifetime = ini_get("session.gc_maxlifetime");
// register the new handler
session_set_save_handler(
array(&$this, 'open'),
array(&$this, 'close'),
array(&$this, 'read'),
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, 'gc')
);
register_shutdown_function('session_write_close');
// start the session
session_start();
}
/**
* Deletes all data related to the session
*
* @return void
*/
function stop()
{
$this->regenerate_id();
session_unset();
session_destroy();
}
/**
* Regenerates the session id.
*
* <b>Call this method whenever you do a privilege change!</b>
*
* @return void
*/
function regenerate_id()
{
// saves the old session's id
$oldSessionID = session_id();
// regenerates the id
// this function will create a new session, with a new id and containing the data from the
old session
// but will not delete the old session
session_regenerate_id();
// because the session_regenerate_id() function does not delete the old session,
// we have to delete it manually
$this->destroy($oldSessionID);
}
/**
* Get the number of online users
*
* This is not 100% accurate. It depends on how often the garbage collector is run
*
* @return integer approximate number of users currently online
*/
function get_users_online()
{
// counts the rows from the database
$result = @mysql_fetch_assoc(@mysql_query("
SELECT
COUNT(session_id) as count
FROM session_data
"));
// return the number of found rows
return $result["count"];
}
/**
* Custom open() function
*
* @access private
*/
function open($save_path, $session_name)
{
return true;
}
/**
* Custom close() function
*
* @access private
*/
function close()
{
return true;
}
/**
* Custom read() function
*
* @access private
*/
function read($session_id)
{
// reads session data associated with the session id
// but only if the HTTP_USER_AGENT is the same as the one who had previously written to this
session
// and if session has not expired
$result = @mysql_query("
SELECT
session_data
FROM
session_data
WHERE
session_id = '".$session_id."' AND
http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND
session_expire > '".time()."'
");
// if anything was found
if (is_resource($result) && @mysql_num_rows($result) > 0) {
// return found data
$fields = @mysql_fetch_assoc($result);
// don't bother with the unserialization - PHP handles this automatically
return $fields["session_data"];
}
// if there was an error return an empty string - this HAS to be an empty string
return "";
}
/**
* Custom write() function
*
* @access private
*/
function write($session_id, $session_data)
{
// first checks if there is a session with this id
$result = @mysql_query("
SELECT
*
FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if there is
if (@mysql_num_rows($result) > 0) {
// update the existing session's data
// and set new expiry time
$result = @mysql_query("
UPDATE
session_data
SET
session_data = '".$session_data."',
session_expire = '".(time() + $this->sessionLifetime)."'
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (@mysql_affected_rows()) {
// return true
return true;
}
// if this session id is not in the database
} else {
// insert a new record
$result = @mysql_query("
INSERT INTO
session_data
(
session_id,
http_user_agent,
session_data,
session_expire
)
VALUES
(
'".$session_id."',
'".$_SERVER["HTTP_USER_AGENT"]."',
'".$session_data."',
'".(time() + $this->sessionLifetime)."'
)
");
// if anything happened
if (@mysql_affected_rows()) {
// return an empty string
return "";
}
}
// if something went wrong, return false
return false;
}
/**
* Custom destroy() function
*
* @access private
*/
function destroy($session_id)
{
// deletes the current session id from the database
$result = @mysql_query("
DELETE FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (@mysql_affected_rows()) {
// return true
return true;
}
// if something went wrong, return false
return false;
}
/**
* Custom gc() function (garbage collector)
*
* @access private
*/
function gc($maxlifetime)
{
// it deletes expired sessions from database
$result = @mysql_query("
DELETE FROM
session_data
WHERE
session_expire < '".(time() - $maxlifetime)."'
");
}
}
?>
/**
* A class to handle sessions by using a mySQL database for session related data storage providing
better
* security then the default session handler used by PHP.
*
* To prevent session hijacking, don't forget to use the {@link regenerate_id} method whenever you
do a
* privilege change in your application
*
* <i>Before usage, make sure you use the session_data.sql file from the
<b>install</b> folder to set up the table
* used by the class</i>
*
* After instantiating the class, use sessions as you would normally
*
* This class is an adaptation of John Herren's code from the "Trick out your session
handler" article
* ({@link http://devzone.zend.com/node/view/id/141}) and Chris Shiflett's code from Chapter 8,
Shared Hosting - Pg 78-80,
* of his book - "Essential PHP Security" ({@link http://phpsecurity.org/code/ch08-2})
*
* <i>Note that the class assumes that there is an active connection to a mySQL database and
it does not attempt to create
* one. This is due to the fact that, usually, there is a config file that holds the database
connection related
* information and another class, or function that handles database connection. If this is not how
you do it, you can
* easily adapt the code by putting the database connection related code in the "open"
method of the class.</i>
*
* This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5
License.
* To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/}
or send a letter to
* Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
*
* For more resources visit {@link http://stefangabos.blogspot.com}
*
* @author Stefan Gabos <ix@nivelzero.ro>
* @version 1.0.1 (last revision: August 11, 2006)
* @copyright (c) 2006 Stefan Gabos
* @package dbSession
*/
error_reporting(E_ALL);
class dbSession
{
/**
* Constructor of class
*
* Initializes the class and starts a new session
*
* There is no need to call start_session() after instantiating this class
*
* @param integer $gc_maxlifetime the number of seconds after which data will be seen
as 'garbage' and
* cleaned up on the next run of the gc (garbage
collection) routine
*
* Default is specified in php.ini file
*
* @param integer $gc_probability used in conjunction with gc_divisor, is used to
manage probability that
* the gc routine is started. the probability is
expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100
means that there is
* a 1% chance the the gc routine will be called on
each request
*
* Default is specified in php.ini file
*
* @param integer $gc_divisor used in conjunction with gc_probability, is used to
manage probability
* that the gc routine is started. the probability is
expressed by the formula
*
* probability = $gc_probability / $gc_divisor
*
* So if $gc_probability is 1 and $gc_divisor is 100
means that there is
* a 1% chance the the gc routine will be called on
each request
*
* Default is specified in php.ini file
*
* @return void
*/
function dbSession($gc_maxlifetime = "", $gc_probability = "", $gc_divisor =
"")
{
// if $gc_maxlifetime is specified and is an integer number
if ($gc_maxlifetime != "" && is_integer($gc_maxlifetime)) {
// set the new value
@ini_set('session.gc_maxlifetime', $gc_maxlifetime);
}
// if $gc_probability is specified and is an integer number
if ($gc_probability != "" && is_integer($gc_probability)) {
// set the new value
@ini_set('session.gc_probability', $gc_probability);
}
// if $gc_divisor is specified and is an integer number
if ($gc_divisor != "" && is_integer($gc_divisor)) {
// set the new value
@ini_set('session.gc_divisor', $gc_divisor);
}
// get session lifetime
$this->sessionLifetime = ini_get("session.gc_maxlifetime");
// register the new handler
session_set_save_handler(
array(&$this, 'open'),
array(&$this, 'close'),
array(&$this, 'read'),
array(&$this, 'write'),
array(&$this, 'destroy'),
array(&$this, 'gc')
);
register_shutdown_function('session_write_close');
// start the session
session_start();
}
/**
* Deletes all data related to the session
*
* @return void
*/
function stop()
{
$this->regenerate_id();
session_unset();
session_destroy();
}
/**
* Regenerates the session id.
*
* <b>Call this method whenever you do a privilege change!</b>
*
* @return void
*/
function regenerate_id()
{
// saves the old session's id
$oldSessionID = session_id();
// regenerates the id
// this function will create a new session, with a new id and containing the data from the
old session
// but will not delete the old session
session_regenerate_id();
// because the session_regenerate_id() function does not delete the old session,
// we have to delete it manually
$this->destroy($oldSessionID);
}
/**
* Get the number of online users
*
* This is not 100% accurate. It depends on how often the garbage collector is run
*
* @return integer approximate number of users currently online
*/
function get_users_online()
{
// counts the rows from the database
$result = @mysql_fetch_assoc(@mysql_query("
SELECT
COUNT(session_id) as count
FROM session_data
"));
// return the number of found rows
return $result["count"];
}
/**
* Custom open() function
*
* @access private
*/
function open($save_path, $session_name)
{
return true;
}
/**
* Custom close() function
*
* @access private
*/
function close()
{
return true;
}
/**
* Custom read() function
*
* @access private
*/
function read($session_id)
{
// reads session data associated with the session id
// but only if the HTTP_USER_AGENT is the same as the one who had previously written to this
session
// and if session has not expired
$result = @mysql_query("
SELECT
session_data
FROM
session_data
WHERE
session_id = '".$session_id."' AND
http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND
session_expire > '".time()."'
");
// if anything was found
if (is_resource($result) && @mysql_num_rows($result) > 0) {
// return found data
$fields = @mysql_fetch_assoc($result);
// don't bother with the unserialization - PHP handles this automatically
return $fields["session_data"];
}
// if there was an error return an empty string - this HAS to be an empty string
return "";
}
/**
* Custom write() function
*
* @access private
*/
function write($session_id, $session_data)
{
// first checks if there is a session with this id
$result = @mysql_query("
SELECT
*
FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if there is
if (@mysql_num_rows($result) > 0) {
// update the existing session's data
// and set new expiry time
$result = @mysql_query("
UPDATE
session_data
SET
session_data = '".$session_data."',
session_expire = '".(time() + $this->sessionLifetime)."'
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (@mysql_affected_rows()) {
// return true
return true;
}
// if this session id is not in the database
} else {
// insert a new record
$result = @mysql_query("
INSERT INTO
session_data
(
session_id,
http_user_agent,
session_data,
session_expire
)
VALUES
(
'".$session_id."',
'".$_SERVER["HTTP_USER_AGENT"]."',
'".$session_data."',
'".(time() + $this->sessionLifetime)."'
)
");
// if anything happened
if (@mysql_affected_rows()) {
// return an empty string
return "";
}
}
// if something went wrong, return false
return false;
}
/**
* Custom destroy() function
*
* @access private
*/
function destroy($session_id)
{
// deletes the current session id from the database
$result = @mysql_query("
DELETE FROM
session_data
WHERE
session_id = '".$session_id."'
");
// if anything happened
if (@mysql_affected_rows()) {
// return true
return true;
}
// if something went wrong, return false
return false;
}
/**
* Custom gc() function (garbage collector)
*
* @access private
*/
function gc($maxlifetime)
{
// it deletes expired sessions from database
$result = @mysql_query("
DELETE FROM
session_data
WHERE
session_expire < '".(time() - $maxlifetime)."'
");
}
}
?>
- <?php
- /**
- * A class to handle sessions by using a mySQL database for session related data storage providing
- better
- * security then the default session handler used by PHP.
- *
- * To prevent session hijacking, don't forget to use the {@link regenerate_id} method whenever you
- do a
- * privilege change in your application
- *
- * <i>Before usage, make sure you use the session_data.sql file from the
- <b>install</b> folder to set up the table
- * used by the class</i>
- *
- * After instantiating the class, use sessions as you would normally
- *
- * This class is an adaptation of John Herren's code from the "Trick out your session
- handler" article
- * ({@link http://devzone.zend.com/node/view/id/141}) and Chris Shiflett's code from Chapter 8,
- Shared Hosting - Pg 78-80,
- * of his book - "Essential PHP Security" ({@link http://phpsecurity.org/code/ch08-2})
- *
- * <i>Note that the class assumes that there is an active connection to a mySQL database and
- it does not attempt to create
- * one. This is due to the fact that, usually, there is a config file that holds the database
- connection related
- * information and another class, or function that handles database connection. If this is not how
- you do it, you can
- * easily adapt the code by putting the database connection related code in the "open"
- method of the class.</i>
- *
- * This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 2.5
- License.
- * To view a copy of this license, visit {@link http://creativecommons.org/licenses/by-nc-nd/2.5/}
- or send a letter to
- * Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.
- *
- * For more resources visit {@link http://stefangabos.blogspot.com}
- *
- * @author Stefan Gabos <ix@nivelzero.ro>
- * @version 1.0.1 (last revision: August 11, 2006)
- * @copyright (c) 2006 Stefan Gabos
- * @package dbSession
- */
- error_reporting(E_ALL);
- class dbSession
- {
- /**
- * Constructor of class
- *
- * Initializes the class and starts a new session
- *
- * There is no need to call start_session() after instantiating this class
- *
- * @param integer $gc_maxlifetime the number of seconds after which data will be seen
- as 'garbage' and
- * cleaned up on the next run of the gc (garbage
- collection) routine
- *
- * Default is specified in php.ini file
- *
- * @param integer $gc_probability used in conjunction with gc_divisor, is used to
- manage probability that
- * the gc routine is started. the probability is
- expressed by the formula
- *
- * probability = $gc_probability / $gc_divisor
- *
- * So if $gc_probability is 1 and $gc_divisor is 100
- means that there is
- * a 1% chance the the gc routine will be called on
- each request
- *
- * Default is specified in php.ini file
- *
- * @param integer $gc_divisor used in conjunction with gc_probability, is used to
- manage probability
- * that the gc routine is started. the probability is
- expressed by the formula
- *
- * probability = $gc_probability / $gc_divisor
- *
- * So if $gc_probability is 1 and $gc_divisor is 100
- means that there is
- * a 1% chance the the gc routine will be called on
- each request
- *
- * Default is specified in php.ini file
- *
- * @return void
- */
- function dbSession($gc_maxlifetime = "", $gc_probability = "", $gc_divisor =
- "")
- {
- // if $gc_maxlifetime is specified and is an integer number
- if ($gc_maxlifetime != "" && is_integer($gc_maxlifetime)) {
- // set the new value
- @ini_set('session.gc_maxlifetime', $gc_maxlifetime);
- }
- // if $gc_probability is specified and is an integer number
- if ($gc_probability != "" && is_integer($gc_probability)) {
- // set the new value
- @ini_set('session.gc_probability', $gc_probability);
- }
- // if $gc_divisor is specified and is an integer number
- if ($gc_divisor != "" && is_integer($gc_divisor)) {
- // set the new value
- @ini_set('session.gc_divisor', $gc_divisor);
- }
- // get session lifetime
- $this->sessionLifetime = ini_get("session.gc_maxlifetime");
- // register the new handler
- session_set_save_handler(
- array(&$this, 'open'),
- array(&$this, 'close'),
- array(&$this, 'read'),
- array(&$this, 'write'),
- array(&$this, 'destroy'),
- array(&$this, 'gc')
- );
- register_shutdown_function('session_write_close');
- // start the session
- session_start();
- }
- /**
- * Deletes all data related to the session
- *
- * @return void
- */
- function stop()
- {
- $this->regenerate_id();
- session_unset();
- session_destroy();
- }
- /**
- * Regenerates the session id.
- *
- * <b>Call this method whenever you do a privilege change!</b>
- *
- * @return void
- */
- function regenerate_id()
- {
- // saves the old session's id
- $oldSessionID = session_id();
- // regenerates the id
- // this function will create a new session, with a new id and containing the data from the
- old session
- // but will not delete the old session
- session_regenerate_id();
- // because the session_regenerate_id() function does not delete the old session,
- // we have to delete it manually
- $this->destroy($oldSessionID);
- }
- /**
- * Get the number of online users
- *
- * This is not 100% accurate. It depends on how often the garbage collector is run
- *
- * @return integer approximate number of users currently online
- */
- function get_users_online()
- {
- // counts the rows from the database
- $result = @mysql_fetch_assoc(@mysql_query("
- SELECT
- COUNT(session_id) as count
- FROM session_data
- "));
- // return the number of found rows
- return $result["count"];
- }
- /**
- * Custom open() function
- *
- * @access private
- */
- function open($save_path, $session_name)
- {
- return true;
- }
- /**
- * Custom close() function
- *
- * @access private
- */
- function close()
- {
- return true;
- }
- /**
- * Custom read() function
- *
- * @access private
- */
- function read($session_id)
- {
- // reads session data associated with the session id
- // but only if the HTTP_USER_AGENT is the same as the one who had previously written to this
- session
- // and if session has not expired
- $result = @mysql_query("
- SELECT
- session_data
- FROM
- session_data
- WHERE
- session_id = '".$session_id."' AND
- http_user_agent = '".$_SERVER["HTTP_USER_AGENT"]."' AND
- session_expire > '".time()."'
- ");
- // if anything was found
- if (is_resource($result) && @mysql_num_rows($result) > 0) {
- // return found data
- $fields = @mysql_fetch_assoc($result);
- // don't bother with the unserialization - PHP handles this automatically
- return $fields["session_data"];
- }
- // if there was an error return an empty string - this HAS to be an empty string
- return "";
- }
- /**
- * Custom write() function
- *
- * @access private
- */
- function write($session_id, $session_data)
- {
- // first checks if there is a session with this id
- $result = @mysql_query("
- SELECT
- *
- FROM
- session_data
- WHERE
- session_id = '".$session_id."'
- ");
- // if there is
- if (@mysql_num_rows($result) > 0) {
- // update the existing session's data
- // and set new expiry time
- $result = @mysql_query("
- UPDATE
- session_data
- SET
- session_data = '".$session_data."',
- session_expire = '".(time() + $this->sessionLifetime)."'
- WHERE
- session_id = '".$session_id."'
- ");
- // if anything happened
- if (@mysql_affected_rows()) {
- // return true
- return true;
- }
- // if this session id is not in the database
- } else {
- // insert a new record
- $result = @mysql_query("
- INSERT INTO
- session_data
- (
- session_id,
- http_user_agent,
- session_data,
- session_expire
- )
- VALUES
- (
- '".$session_id."',
- '".$_SERVER["HTTP_USER_AGENT"]."',
- '".$session_data."',
- '".(time() + $this->sessionLifetime)."'
- )
- ");
- // if anything happened
- if (@mysql_affected_rows()) {
- // return an empty string
- return "";
- }
- }
- // if something went wrong, return false
- return false;
- }
- /**
- * Custom destroy() function
- *
- * @access private
- */
- function destroy($session_id)
- {
- // deletes the current session id from the database
- $result = @mysql_query("
- DELETE FROM
- session_data
- WHERE
- session_id = '".$session_id."'
- ");
- // if anything happened
- if (@mysql_affected_rows()) {
- // return true
- return true;
- }
- // if something went wrong, return false
- return false;
- }
- /**
- * Custom gc() function (garbage collector)
- *
- * @access private
- */
- function gc($maxlifetime)
- {
- // it deletes expired sessions from database
- $result = @mysql_query("
- DELETE FROM
- session_data
- WHERE
- session_expire < '".(time() - $maxlifetime)."'
- ");
- }
- }
- ?>
I'd love to change the world, but they won't give me the source code.
Page 1 of 1
To Reply to this topic you need to LOGIN or REGISTER. It is free.
Post Information
- Total Posts in this topic: 2 posts
- Users browsing this forum: No registered users and 126 guests
- You cannot post new topics in this forum
- You cannot reply to topics in this forum
- You cannot edit your posts in this forum
- You cannot delete your posts in this forum
- You cannot post attachments in this forum
