Giter Club home page Giter Club logo

voku / session2db Goto Github PK

View Code? Open in Web Editor NEW

This project forked from bdewong/zebra_session

29.0 7.0 7.0 183 KB

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

License: GNU Lesser General Public License v3.0

PHP 100.00%
session-management php session-store sessionstorage sessionstore hacktoberfest

session2db's Introduction

Build Status Coverage Status Codacy Badge Latest Stable Version Total Downloads License Donate to this project using Paypal Donate to this project using Patreon

๐Ÿ‘‘ 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)
    );
    
    // you can also use you own database implementation via the "Db4Session"-interface,
    // take a look at the "DbWrapper4Session"-class for a example
    $db_wrapper = new DbWrapper4Session($db);
    
    // initialize "Session to DB"
    new Session2DB(
      'add_your_own_security_code_here', // security_code
      0,                                 // session_lifetime
      false,                             // lock_to_user_agent 
      false,                             // lock_to_ip
      1,                                 // gc_probability 
      1000,                              // gc_divisor 
      'session_data',                    // table_name
      60,                                // lock_timeout 
      $db_wrapper,                       // db (must implement the "Db4Session"-interface)
      true                               // start_session (start the session-handling automatically, otherwise you need to use session2db->start() afterwards)
    );

    // 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!

Support

For support and donations please visit Github | Issues | PayPal | Patreon.

For status updates and release announcements please visit Releases | Twitter | Patreon.

For professional support please contact me.

Thanks

  • Thanks to GitHub (Microsoft) for hosting the code and a good infrastructure including Issues-Managment, etc.
  • Thanks to IntelliJ as they make the best IDEs for PHP and they gave me an open source license for PhpStorm!
  • Thanks to Travis CI for being the most awesome, easiest continous integration tool out there!
  • Thanks to StyleCI for the simple but powerfull code style check.
  • Thanks to PHPStan && Psalm for relly great Static analysis tools and for discover bugs in the code!

session2db's People

Contributors

bdewong avatar dependabot-support avatar nightsh avatar stefangabos avatar voku avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

session2db's Issues

[Insight] exit() and die() functions should be avoided - in src/voku/helper/Session2DB.php, line 662

in src/voku/helper/Session2DB.php, line 662

This line stops the execution flow, without explanation. If this is for debug, you should remove it. If this is to deal with an error, use exceptions instead.

    $result_lock = $this->db->query($query_lock);

    // if there was an error
    // stop execution
    if (!is_object($result_lock) || $result_lock->num_rows != 1) {
      die('Session: Could not obtain session lock!');
    }

    //  reads session data associated with a session id, but only if
    //  -   the session ID exists;
    //  -   the session has not expired;

Posted from SensioLabsInsight

Support for Galera Cluster

Galera Cluster has some limitations. One of them is not supporting GET_LOCK and RELEASE_LOCK.

From there website:

Unsupported explicit locking include LOCK TABLES, FLUSH TABLES {explicit table list} WITH READ LOCK, (GET_LOCK(), RELEASE_LOCK(),โ€ฆ). Using transactions properly should be able to overcome these limitations. Global locking operators like FLUSH TABLES WITH READ LOCK are supported.
(https://mariadb.com/kb/en/library/mariadb-galera-cluster-known-limitations/)

This prevents us from using session2db as a session-implementation at the moment.

Is there a plan to support Galera Cluster soon?

Integrity constraint violation

This is my config:

    $dbWrapper = new PDOMySQLSession();
    $session2DB = new Session2DB(
        '',
        $sessionLifetime,
        false,
        false,
        1,
        1000,
        'session_data',
        60,
        $dbWrapper,
        false
    );
    $session2DB->use_lock_via_mysql(null);
    return $session2DB->start();

I use version 2.1.2 of session2db.
I also use galera cluster as my mysql setup.
In general it works.

But i often get this error:

2018/01/16 16:50:10 [error] 789#789: *13705337 FastCGI sent in stderr: "PHP message: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'session_c0afbf3691e8cd2d85ec2e38ea52ae2441
1e3b4d' for key 'PRIMARY' in /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php:65
Stack trace:
#0 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php(65): PDO->query('\n      INSERT I...')
#1 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(418): churchtools\PDOMySQLSession->query('\n      INSERT I...')
#2 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(373): voku\helper\Session2DB->_get_lock_mysql_fake('session_c0afbf3...', '1516117870'
)
#3 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(723): voku\helper\Session2DB->_get_lock('92jS" while reading response header from upstream, client: 192.168.20.1, server: ~^(?P<sub>.+)\.church\.tools$, request: "POST /index.php?q=churchservice/ajax HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "testanne.church.tools", referrer: "https://testanne.church.tools/?q=churchservice"

And also this:

2018/01/16 16:54:33 [error] 724#724: *14467437 FastCGI sent in stderr: "PHP message: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'session_c0afbf3691e8cd2d85ec2e38ea52ae2441
1e3b4d' for key 'PRIMARY' in /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php:65
Stack trace:
#0 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php(65): PDO->query('\n      INSERT I...')
#1 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(418): churchtools\PDOMySQLSession->query('\n      INSERT I...')
#2 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(373): voku\helper\Session2DB->_get_lock_mysql_fake('session_c0afbf3...', '1516118133'
)
#3 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(723): voku\helper\Session2DB->_get_lock('92jS" while reading response header from upstream, client: 192.168.20.3, server: ~^(?P<sub>.+)\.church\.tools$, request: "POST /index.php?q=churchservice/ajax HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "testanne.church.tools", referrer: "https://testanne.church.tools/?q=churchservice"
2018/01/16 16:54:33 [error] 724#724: *14467797 FastCGI sent in stderr: "PHP message: PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; try restarting transaction in /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php:65
Stack trace:
#0 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/classes/churchtools/PDOMySQLSession.php(65): PDO->query('\n      INSERT I...')
#1 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(418): churchtools\PDOMySQLSession->query('\n      INSERT I...')
#2 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(373): voku\helper\Session2DB->_get_lock_mysql_fake('session_c0afbf3...', '1516118133')
#3 /opt/churchtools_application/versions/churchtools-3.26.0-RC1/system/composer/voku/session2db/src/voku/helper/Session2DB.php(723): voku\helper\Session2DB->_get_lock('92jSrGhDJGiJTqs...')
#4 [intern" while reading response header from upstream, client: 192.168.20.3, server: ~^(?P<sub>.+)\.church\.tools$, request: "POST /index.php?q=churchdb/ajax HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "testanne.church.tools", referrer: "https://testanne.church.tools/?q=churchservice"

Connection using DBAL

How to use doctrine/dbal or nextras/dbal for connection in getInstance?

DB::getInstance('localhost', 'andy', 'andy', 'database');

I've try using doctrine dbal but don't work!!!

Loading without composer?

How? Not a fan of composer. Whats the right order to load these classes in?

 PHP Fatal error:  Uncaught Error: Interface "helper\Db4Session" not found 

Edit; even with composer im running into issues; I see its noted

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

Okay then, how is this class expecting the connection to be made? like $mysqli = new mysqli(); or?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.