ADOdb

Database Abstraction Layer for PHP

User Tools

Site Tools


v6:dbsessions

V6 Session Management Service

The Session Management service requires PHP 7.4 or higher

Overview

The Session Management service provides the means to store session data in a database. It extends the normal PHP SessionHandler class, enhancing flexibility, security and the means to store session data server side instead of client side.

As with all session management, each session encapsulates all of the tabs open to a single site on a single browser on a single machine.

Prerequisites

The feature requires a PSR compliant auto-loader. The feature exist in the ADOdb namespace.

Upgrading From Version 5

  • The V6 service no longer supports storing the session data in VARCHAR type columns. The data must be stored in a BLOB type column.
  • The data is stored by default in the standard PHP Serialize format. The function adodb_unserialize() is no longer needed
  • Different PHP scripts are no longer required to run encryption or compression.
  • The number of supported databases has been expanded
  • The session management system no longer relies on its own connection, but instead uses a previously established ADOdb object. This allows you to use complex connections such as MySQL using SSL
  • Access to the class is no longer made using static methods. Instead normal class methods are used.

Building The Table

The directory /ADOdb/addins/session/support contains sample SQL files to build a suitable table for each database type.

The ADOSessionDefinitions File

The \ADOdb\addins\session\ADOSessionDefinitions.php file contains the definitions required to manage sessions inside the database. To activate the sessions instantiate or copy the class

final class ADOSessionDefinitions
{
 
	/*
	* Defines if sessions debugging is enabled. Not the same
	* as database driver debugging. Critical logging operations
	* ignore this flag if there is a logging method attached
	*/
	public bool $debug = false;
 
	/*
	* Attach an ADOdb logging object here
	*/
	public ?object $loggingObject = null;
 
	/*
	* Is the session connection readonly
	*/
	public bool $readOnly = false;
 
	/*
	* Defines the sessions table name
	*/
	public string $tableName = 'sessions2';
 
	/*
	* Most databases require large object handling if we are using compression
	*/
	public ?string $largeObject = 'blob';
 
	/*
	* What fields will be retrieved from the database on
	* read
	*/
	public string $readFields = 'sessdata';
 
	/*
	* Defines the crypto method. Default none
	*/
	const CRYPTO_NONE 	= 0;
	const CRYPTO_MD5  	= 1;
	const CRYPTO_MCRYPT = 2;
	const CRYPTO_SHA1   = 3;
	const CRYPTO_SECRET = 4;
 
	public int $cryptoMethod = 0;
 
	/*
	* Defines the compression method - Default none
	*/
	const COMPRESS_NONE = 0;
	const COMPRSS_BZIP  = 1;
	const COMPRESS_GZIP = 2;
 
	public int $compressionMethod = 0;
 
	/*
	* Serialization methods
	*/
	const SER_DEFINED 	 	   = 0;
	const SER_PHP		 	   = 1;
	const SER_PHP_BINARY	   = 2;
	const SER_PHP_SERIALIZABLE = 3;
	const SER_PHP_WDDX 		   = 4;
 
	public ?int $serializationMethod = 3;
 
	/*
	* You can activate this for MySQL or Postgres if you want,
	* but it is no longer recommended to do so
	*/
	public bool $optimizeTable = false;
 
 
	/**
	* Constructor
	*
	*/
	public function __construct(){}
 
}

The Definitions

bool $debug

$debug

This value Defines if sessions debugging is enabled. A functioning $errorHandler must have already been created and instantiated to trap non-debugging messages. This flag then allows the handler to trap debugging messages. The messages sent by the debugging channel are not the same as the debugging flag set on the connection, and can be handled independently.

object $loggingObject

$loggingObject

The logging object is the name of a previously instantiated logging class that will be used to trap critical or other errors inside the Session Handler. In addition it can be used for debugging

bool $readOnly

$readOnly

If set, then a new session cannot be created or existing one updated. Only the existing session data can be read

string $tableName = 'sessions2'

$tableName

By default, the name of the table used to manage the sessions is sessions2, but you can change the value in the definitions file for any reason

string $readfields='sessdata'

$readFields

By default, only the sessdata column is retrieved by the class. If you change the name of the column you can re-specify it here, or alternatively change it to a CSV list to retrieve multiple columns.

int $cryptoMethod

Crypto Method

By default, the session data is written to the database as a plain-text, serialized array. If you wish to protect it, you can apply one of the encryption methods set below.

NameValueDescription
CRYPTO_NONE0Default. No encryption made
CRYPTO_MD51Uses the MD5 library
CRYPTO_MCRYPT2Uses the MCrypt library
CRYPTO_SHA13Uses the SHA1 Library
CRYPTO_SECRET4Uses the Secret Library

Note that there is an impact on performance, because the sessdata column would need to be decrypted and encrypted on each operation.

int $compressionMethod

Compression Method

By default, the sessdata is written to the database uncompressed, but if you wish to save space or save large amounts of data, you can use one of the compression methods below.

NameValueDescription
COMPRESS_NONE0Default No compression
COMPRSS_BZIP1Use the BZIP library
COMPRESS_GZIP2Use the GZIP library

Note that there is an impact on performance, because the sessdata column would need to be decompressed and re-compressed on each operation

int $serializationMethod

Serialization Method

NameValueDescription
SER_DEFINED0Older Method
SER_PHP1Older method used in previous versions of Session Management
SER_PHP_BINARY2Older Binary method
SER_PHP_SERIALIZABLE3Default Use the standard PHP serialize method
SER_PHP_WDDX4Serialize using the WDDX method. Requires Additional, non-standard libraries

For more information on serialization See Here

bool $optimizeTable

Optimize Table

Table optimization is a feature used in PostgreSQL and previously MySQL, to improve performance.

  • Other databases ignore this value if set
  • MySQL no longer recommends use of this parameter

Complex Example

In this example we will use both compression and encryption, as well as full monolog logging options on both the connection and session object. The code assumes that the autoloader has already been provided

 
/**
* Step 1, create a logging class using the appropriate method.
* In this case, we will add the monolog classes
*/
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
 
$debugStreamHandler    = new StreamHandler('/home/logs/debug.log', 
                                           Logger::DEBUG,
                                           $bubble=false);
$noticeStreamHandler = new StreamHandler('/home/logs/notice.log', 
                                         Logger::NOTICE,
                                         $bubble=false);
$criticalStreamHandler = new StreamHandler('/home/logs/critical.log', 
                                           Logger::CRITICAL,
                                           $bubble=false);
 
$streamHandlers = array(Logger::DEBUG=>$debugStreamHandler,
                        Logger::NOTICE=>$noticeStreamHandler,
			Logger::CRITICAL=>$criticalStreamHandler
                       );
 
/*
* Use the defined handlers to log messages from the core application
*/
$coreLDef = new ADOdb\addins\logger\plugins\monolog\ADOLoggingDefinitions;
$coreLDef->streamHandlers = $streamHandlers;
$coreLDef->loggingTag = 'ADODB-CORE';
 
$coreLoggingObject = new ADOdb\addins\logger\ADOCoreLogger($coreLDef);
$coreLoggingObject->logBacktrace = true;
 
/*
* Use the same handlers to log messages from the session module
*/
$loggingDefinition = new ADOdb\addins\logger\plugins\monolog\ADOLoggingDefinitions;
$loggingDefinition->streamHandlers = $streamHandlers;
$loggingDefinition->loggingTag = 'ADODB-SESSION';
$asdLoggingObject = new ADOdb\logger\ADOLogger($loggingDefinition);
 
/**
* Step 2: Establish an ADOdb session that will provide the connection for
* session management. This can either be a shared session with 
* other uses, or a standalone connection
*/
include '/ADOdb/adodb.inc.php';
$db = newAdoConnection('mysqli');
$db->connect('localhost',"adodb","adodb",'sessions');
 
 
/**
* Step 3: Create a session definition object,choose the 
* compression and crypto method and attach the previously
* defined logging class to funnel messages into
*/
$asd = new ADOdb\addins\session\ADOSessionDefinitions;
$asd->compressionMethod = $asd::COMPRESS_GZIP;
$asd->cryptoMethod = $asd::CRYPTO_SHA1;
$asd->loggingObject = $asdLoggingObject;
 
 
/*
* Create a base session management object
*/
$sessionHandler = new ADOdb\addins\session\ADOSession();
 
/**
* Step 4: Establish a session, passing the established database connection, and
* the session configuration object we can then use to modify 
* runtime parameters
*/
$session = $sessionHandler->startSession($db,$asd);
/*
* Set the session lifetime
*/
$session->lifetime(2880);
 
session_start();
 
/*
* Write session variables, as we refresh the page, the
* counter will increment
*/
if (isset($_SESSION['data']['counter']))
	$counter = $_SESSION['data']['counter'] + 1;
else
	$counter = 0;
 
$_SESSION['name'] = 'SOME ARBITARY STRING';
$_SESSION['data'] = array(
    'bird'=>'chicken',
    'reptile'=>'paper',
    'counter'=>$counter);
v6/dbsessions.txt · Last modified: by 127.0.0.1