PHP Classes
elePHPant
Icontem

PHP Session MySQL Handler: Handler for storing session data in MySQL

Recommend this page to a friend!
  Info   View files Documentation   View files View files (18)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2017-12-15 (2 days ago) RSS 2.0 feedStarStarStarStar 64%Total: 322 This week: 30All time: 6,959 This week: 14Up
Version License PHP version Categories
session2db 1.0.24GNU General Publi...5.3PHP 5, Databases, User Management
Description Author

This class implements a handler for storing session data in MySQL.

This is class based on Zebra_Session from Stefan Gabos that registers session handler functions to store and retrieve session data from MySQL databases using MySQLi.

It uses row locks to lock only individual session database table records while the current script session is being accessed.

Innovation Award
PHP Programming Innovation award nominee
April 2017
Number 2
By default PHP stores information of session variables in files, but applications can provide their own session handlers and store session data in other storage containers like databases. It is common to store session data in MySQL databases.

One issue to be concerned with sessions is that only one script can change session data at a time of a given user.

For databases, transactions could be used to prevent that multiple scripts try to change the same user session data in a way that could cause inconsistency.

However, the use of sessions may cause that the table that contains session data records locks the access to session records of all users.

This class provides a better solution by using row level locking, thus allowing that session records of different users be changed at the same time by different scripts.

Manuel Lemos
  Performance   Level  
Name: Lars Moelleken <contact>
Classes: 17 packages by
Country: Germany Germany
Age: 30
All time rank: 133084 in Germany Germany
Week rank: 7 Up1 in Germany Germany Up
Innovation award
Innovation award
Nominee: 8x

Details

Join the chat at https://gitter.im/voku/session2db Build Status Coverage Status Scrutinizer Code Quality Codacy Badge SensioLabsInsight Dependency Status Latest Stable Version Total Downloads Latest Unstable Version PHP 7 ready License

Session2DB

A drop-in replacement for PHP's default session handler which stores session data in a database, providing both better performance and better security and protection against session fixation and session hijacking.

Session2DB implements session locking - a way to ensure that data is correctly handled in a scenario with multiple concurrent AJAX requests.

It is also a solution for applications that are scaled across multiple web servers (using a load balancer or a round-robin DNS) and where the user's session data needs to be available. Storing sessions in a database makes them available to all of the servers!

The library supports "flashdata" - session variable which will only be available for the next server request, and which will be automatically deleted afterwards. Typically used for informational or status messages (for example: "data has been successfully updated").

Session2DB is was inspired by John Herren's code from the Trick out your session handler article and Chris Shiflett's articles about PHP sessions and based on Zebra_Session.

The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to E_ALL.

Requirements

PHP 7.x with the mysqli extension activated, MySQL 5.x+ (recommanded: mysqlnd extension)

How to install

composer require voku/session2db

How to use

After installing, you will need to initialise the database table from the install directory from this repo, it will containing a file named session_data.sql. This file contains the SQL code that will create a table that is used by the class to store session data. Import or execute the SQL code using your preferred MySQL manager (like phpMyAdmin or the fantastic Adminer) into a database of your choice.

*Note that this class assumes that there is an active connection to a MySQL database and it does not attempt to create one!

//
// simple (dirty) example
//

<?php
    use voku\db\DB;
    use voku\helper\Session2DB;
    
    DB::getInstance('hostname', 'username', 'password', 'database');
    new Session2DB();
    
    // from now on, use sessions as you would normally
    // this is why it is called a "drop-in replacement" :)
    $_SESSION['foo'] = 'bar';

//
// extended example
//

<?php
    use voku\db\DB;
    use voku\helper\DbWrapper4Session;
    use voku\helper\Session2DB;

    // include autoloader
    require_once 'composer/autoload.php';

    // initialize the database connection e.g. via "voku\db\DB"-class
    $db = DB::getInstance(
        'hostname', // e.g. localhost
        'username', // e.g. user_1
        'password', // e.g. 
        'database', // e.g. db_1
        'port',     // e.g. 3306
        'charset',  // e.g. utf8mb4
        true,       // e.g. true|false (exit_on_error)
        true,       // e.g. true|false (echo_on_error)
        '',         // e.g. 'framework\Logger' (logger_class_name)
        '',         // e.g. 'DEBUG' (logger_level)
        array(
            'session_to_db' => true,
        )
    );
    
    // you can also use you own database implementation via the "Db4Session"-interface,
    // take a look at the "DbWrapper4Session"-class for a example
    $dbWrapper = new DbWrapper4Session($db);
    
    // initialize "Session to DB"
    new Session2DB(
      'add_your_own_security_code_here', // security_code
      '',                                // session_lifetime
      false,                             // lock_to_user_agent 
      false,                             // lock_to_ip
      1,                                 // gc_probability 
      1000,                              // gc_divisor 
      'session_data',                    // table_name
      60,                                // lock_timeout 
      $dbWrapper                         // db (must implement the "Db4Session"-interface)
    );

    // from now on, use sessions as you would normally
    // this is why it is called a "drop-in replacement" :)
    $_SESSION['foo'] = 'bar';

    // data is in the database!
  Files folder image Files  
File Role Description
Files folder imageinstall (2 files)
Files folder imagesrc (1 directory)
Files folder imagetests (4 files)
Accessible without login Plain text file .editorconfig Data Auxiliary data
Accessible without login Plain text file .scrutinizer.yml Data Auxiliary data
Accessible without login Plain text file .styleci.yml Data Auxiliary data
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file CHANGELOG.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file license.txt Doc. Documentation
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation

  Files folder image Files  /  install  
File Role Description
  Accessible without login Plain text file lock_data.sql Data Auxiliary data
  Accessible without login Plain text file session_data.sql Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imagevoku (1 directory)

  Files folder image Files  /  src  /  voku  
File Role Description
Files folder imagehelper (3 files)

  Files folder image Files  /  src  /  voku  /  helper  
File Role Description
  Plain text file Db4Session.php Class Class source
  Plain text file DbWrapper4Session.php Class Class source
  Plain text file Session2DB.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Accessible without login Plain text file bootstrap.php Aux. Auxiliary script
  Plain text file SimpleSessionLockViaExtraTableTest.php Class Class source
  Plain text file SimpleSessionLockViaMySqlTest.php Class Class source
  Plain text file SimpleSessionLockViaPhpTest.php Class Class source

Downloadsession2db-2017-12-15.zip 22KB
Downloadsession2db-2017-12-15.tar.gz 16KB
Install with ComposerInstall with Composer
Needed packages  
Class DownloadWhy it is needed Dependency
Simple MySQLi Class Download .zip .tar.gz for the DB connect Required
 Version Control Unique User Downloads Download Rankings  
 100%
Total:322
This week:30
All time:6,959
This week:14Up
 User Ratings  
 
 All time
Utility:91%StarStarStarStarStar
Consistency:100%StarStarStarStarStarStar
Documentation:91%StarStarStarStarStar
Examples:-
Tests:-
Videos:-
Overall:64%StarStarStarStar
Rank:822