Zebra_Session, a wrapper for PHP’s default session handling functions, using MySQL for storage

Get the latest updates on this PHP library via RSS

Session support in PHP consists of a way to preserve information (variables) on subsequent accesses to a website’s pages. Unlike cookies, variables are not stored on the user’s computer. Instead, only a session identifier is stored in a cookie on the visitor’s computer, which is matched up with the actual session data kept on the server, and made available to us through the $_SESSION super-global. Session data is retrieved as soon as we open a session, usually at the beginning of each page.

By default, session data is stored on the server in flat files, separate for each session. The problem with this scenario is that performance degrades proportionally with the number of session files existing in the session directory (depending on the server’s operating system’s ability to handle directories with numerous files). Another issue is that session files are usually stored in a location that is world readable posing a security concern on shared hosting.

This is where Zebra_Session comes in handy – a PHP library that acts as a drop-in replacement for PHP’s default session handler, but instead of storing session data in flat files it stores them in a MySQL database, providing better security and better performance.

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

Supports “flashdata” – session variables 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”).

This class is was inspired by John Herren’s code from the Trick out your session handler article and Chris Shiflett’s code from his book Essential PHP Security, chapter 8, Shared Hosting, Pg. 78-80.

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

Starting with version 2.0, Zebra_Session implements row locks, ensuring that data is correctly handled in a scenario with multiple concurrent AJAX requests.

Citing from Race Conditions with Ajax and PHP Sessions, a great article by Andy Bakun:

When locking is not used, multiple requests (represented in these diagrams as processes P1, P2 and P3) access the session data without any consideration for the other processes and the state of the session data. The running time of the requests are indicated by the height of each process’s colored area (the actual run times are unimportant, only the relative start times and durations).

Session access without locking

In the example above, no matter how P2 and P3 change the session data, the only changes that will be reflected in the session are those that P1 made because they were written last. When locking is used, the process can start up, request a lock on the session data before it reads it, and then get a consistent read of the session once it acquires exclusive access to it. In the following diagram, all reads occur after writes:

Session access with locking

The process execution is interleaved, but access to the session data is serialized. The process is waiting for the lock to be released during the period between when the process requests the session lock and when the session is read. This means that your session data will remain consistent, but it also means that while processes P2 and P3 are waiting for their turn to acquire the lock, nothing is happening. This may not be that important if all of the requests change or write to the session data, but if P2 just needs to read the session data (perhaps to get a login identifier), it is being held up for no reason.

So, in the end, this is not the best solution but still is better than nothing. The best solution is probably a per-variable locking. You can read a very detailed article about all this in Andy Bakun‘s article Race Conditions with Ajax and PHP Sessions.

Thanks to Michael Kliewe who brought this to my attention!


Features review

  • acts as a wrapper for PHP’s default session handling functions, but instead of storing session data in flat files it stores them in a MySQL database, providing better security and better performance
  • it is a drop-in and seemingless replacement for PHP’s default session handler: PHP sessions will be used in the same way as prior to using the library; you don’t need to change any existing code!
  • implements row locks, ensuring that data is correctly handled in scenarios with multiple concurrent AJAX requests
  • because session data is stored in a database, the library represents a solution for applications that are scaled across multiple web servers (using a load balancer or a round-robin DNS)
  • has comprehensive documentation
  • the code is heavily commented and generates no warnings/errors/notices when PHP’s error reporting level is set to E_ALL


PHP 5.1.0+, MySQL 4.1.22+



Download the latest version, unpack it, and put it in a place accessible to your scripts. After unpacking, you will notice a directory called “install” 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.


How to use

Note that this class assumes that there is an active connection to a MySQL database and it does not attempt to create one! If you really need the class to make a database connection, put the code in the “open” method of the class.


    // first, connect to a database containing the sessions table

    // include the Zebra_Session class
    include 'path/to/Zebra_Session.php';

    // instantiate the class
    // this also calls session_start()
    $session = new Zebra_Session;

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




version 2.1.4

If you find this library to be useful to you, you can support the author by donating a small amount via PayPal:

Alternatively, you could show your support by starring this library on GitHub

Zebra_Session is distributed under the LGPL.

In plain English, this means that you have the right to view and to modify the source code of this software, but if you modify and distribute it, you are required to license your copy under a LGPL-compatible license, and to make the entire source code of your derivation available to anybody you distribute the software to.

You also have the right to use this software together with software that has different licensing terms (including, but not limited to, commercial and closed-source software), and distribute the combined software, as long as state that your software contains portions licensed under the LGPL license, and provide information about where the LGPL licensed software can be downloaded.

If you distribute copies of this software you may not change the copyright or license of this software.

You may also like:



Documentation Become a ninja.
Read the comprehensive documentation.



Click on a version to expand/collapse information.

version 2.1.4 (February 19, 2016)
  • fixed an issue when using the library with Composer
version 2.1.1 (September 25, 2014)
  • this version makes use of a feature introduced in PHP 5.1.0 for the “regenerate_id” method; thanks to Fernando Sávio; this also means that now the library requires PHP 5.1.0+ to work
version 2.1.0 (August 02, 2013)
  • dropped support for PHP 4; minimum required version is now PHP 5;
  • dropped support for PHP’s mysql extension, which is officially deprecated as of PHP v5.5.0 and will be removed in the future; the extension was originally introduced in PHP v2.0 for MySQL v3.23, and no new features have been added since 2006; the library now relies on PHP’s mysqli extension;
  • because of the above, the order of the arguments passed to the constructor have changed and now the “link” argument comes first, as with the mysqli extension this now needs to be explicitly given;
  • added support for “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”); see the newly added set_flashdata method; thanks Andrei Bodeanschi for suggesting!;
  • the project is now available on GitHub and also as a package for Composer;
version 2.0.4 (January 19, 2013)
  • previously, session were always tied to the user agent used when the session was first opened; while this is still true, now this behavior can be disabled by setting the constructor‘s new “lock_to_user_agent” argument to FALSE; why? because in certain scenarios involving Internet Explorer, the browser will randomly change the user agent string from one page to the next by automaticaly switching into compatilibity mode; thanks to Andrei Bodeanschi;
  • also, the constructor has another new “lock_to_ip” argument with which a session can be restricted to the same IP as when the session was first opened – use this with caution as many ISPs provide dynamic IP addresses which change over time, not to mention users who come through proxies; this is mostly useful if you know your users come from static IPs;
  • for better protection against session hijacking, the first argument of the constructor is now mandatory;
  • altered the table structure;
  • because the table’s structure has changed as well as the order of the arguments in the constructor, you’ll have to change a few things when switching to this version from a previous one;
  • some documentation refinements;
version 2.0.3 (July 13, 2012)
  • fixed a bug where sessions’ life time was twice longer than expected; thanks to Andrei Bodeanschi;
  • details on how to preserve session data across sub domains was added to the documentation;
  • the messages related database connection errors are now more meaningful;
version 2.0.2 (October 24, 2011)
  • fixed a bug with the get_active_sessions() method which was not working at all;
  • fixed a bug where the script was not using the provided MySQL link identifier (if available);
version 2.0.1 (July 03, 2011)
  • the constructor method now accepts an optional link argument which must be a MySQL link identifier. By default, the library made use of the last link opened by mysql_connect(). On some environments (particularly on a shared hosting) the “last link opened by mysql_connect” was not available at the time of the instantiation of the Zebra_Session library. For these cases, supplying the MySQL link identifier to the constructor method will fix things. Thanks to Mark for reporting.
  • some documentation refinements
version 2.0 (April 18, 2011)
  • the class now implements session locking; session locking is a way to ensure that data is correctly handled in a scenario with multiple concurrent AJAX requests; thanks to Michael Kliewe for suggesting this and to Andy Bakun for this excellent article on the subject Race Conditions with Ajax and PHP Sessions.
version 1.0.8 (December 27, 2010)
  • fixed a small bug in the destroy method; thanks to Tagir Valeev for reporting;
  • the script would trigger a PHP notice if the HTTP_USER_AGENT value was not available in the $_SERVER super-global;
  • added a new method “get_settings” that returns the default session-related settings for the environment where the class is used
version 1.0.7 (October 29, 2008)
  • the class will now trigger a fatal error if a database connection is not available;
  • the class will now report if MySQL table is not available;
version 1.0.6 (October 01, 2007)
  • the constructor of the class now accepts a new argument: tableName – with this, the MySQL table used by the class can be changed;
version 1.0.5 (September 15, 2007)
  • ‘LIMIT 1’ added to the read method improving the performance of the script; thanks to A. Leeming for suggesting this;
version 1.0.4 (August 23, 2007)
  • rewritten the write method which previously had to run two queries each time; it now only runs a single one, using ON DUPLICATE KEY UPDATE; thanks to Inchul Koo for providing this information;
  • the type of the http_user_agent column in the MySQL table has been changed from TEXT to VARCHAR(32) as now it is an MD5 hash; this should increase the performance of the script; thanks to Inchul Koo for suggesting this;
  • the constructor of the class now accepts a new argument: securityCode, in order to try to prevent HTTP_USER_AGENT spoofing; read the documentation for more information; thanks to Inchul Koo for suggesting this;
version 1.0.3 (December 13, 2006)
  • the get_users_online method is now more accurate as it now runs the garbage collector before getting the number of online users; thanks to Gilles for the tip;
  • the structure of the MySQL table used by the class was tweaked in so that the http_user_agent column has been changed from VARCHAR(255) to TEXT and the session_data column has been changed from TEXT to BLOB; thanks to Gilles for the tip
version 1.0.2 (November 22, 2006)
  • the class was trying to store the session data without mysql_real_escape_string-ing it and therefore, whenever the data to be saved contained quotes, nothing was saved; thanks to Ed Kelly for reporting this;
version 1.0.1 (September 11, 2006)
  • the structure of the MySQL table used by the class was tweaked and now the session_id column is now a primary key and its type has changed from VARCHAR(255) to VARCHAR(32) as it now is an MD5 hash; previously a whole table scan was done every time a session was loaded; thanks to Harry for suggesting this;
  • added a new stop method which deletes a session along with the stored variables from the database; this was introduced because many people were using the private destroy method which is only for internal purposes;
  • the default settings for session.gc_maxlifetime, session.gc_probability and session.gc_divisor can now be overridden through the constructor;
  • on popular request, an example file was added;
version 1.0 (August 01, 2006)
  • initial release


106 responses to “Zebra_Session, a wrapper for PHP’s default session handling functions, using MySQL for storage”

Follow the comments via RSS
  • Atkins Smith, 2015-01-23, 23:46

    I followed all instruction but the session is not store in database. I don’t get any error message.

    Please help.



  • Mark Strange, 2015-04-08, 13:53

    H Stefan,
    Many thanks for this library – I have a question. I have added two new fields to the database, one is a date stamp so I can work out how long a user has been logged in. The other is a user_id so I can easily link to my users table. However I don’t seem to be able to update the user_id field once the user logs in. Is there some sort of record locking going on?

  • Mark, 2015-06-18, 22:35

    Hi Stefan
    I installed Zebra_Session but get an error : Zebra_Session: No MySQL connection!
    But I know that I have a Zebra_Database connection active – when I disable Zebra_Session I can see the Z_D debugbar – the session tables are available in the database.

    Are there a conflict between Zebra_Session and Zebra_Database ?

    Best regards,

  • shrynk, 2015-06-18, 23:00

    At first: Very nice done! Ty for that awesome code.
    Second: Sry for my bad english 🙂

    There might to be a problem in your code. It seems that there is a bug in older versions than MySQL < 5.5.

    I have read about it in the MySql-Reference:

    "If a client attempts to acquire a lock that is already held by another client, it blocks according to the timeout argument. If the blocked client terminates, its thread does not die until the lock request times out. This is a known bug (fixed in MySQL 5.5).
    Bu can you insert MySQLs IS_FREE_LOCK-Function into your
    code, because of a bug in older MySQL-Versions"

    I am gonna to implement it into your class.
    If you need a copy, just send me an e-mail.

    Ty very much for your work 🙂

  • Andre, 2015-12-22, 14:34

    Hi Stefan, thank you so much for your efforts and sharing this class. I use session class with Database class. When i close browser (ie11) and load localhost again, session table insert New row, a new session. However when i wait more than session life time and refresh the page, no new row is inserted. Aren’t they same to close browser OR wait more than expiry duration? I would expect a new row inserted. I am a rookie one and can you please explain me where I am wrong. (i am sure that i misunderstand something.)

  • Ferdinand, 2016-01-29, 08:15

    Love this one!!!!
    Never again a php-session without this great piece of code!
    Thank you very much for this one!!!
    possibly also change the session_name (the perfidious PHPSESSID).
    Cool would be – like the session id – also the session-name changes everytime (e.g. js9a394a7n1h60e2qs1qji2tc2 as Session name instead of PHPSESSID) 😉
    just an idea!

    • Stefan Gabos, 2016-01-29, 09:43

      I am glad you like it! Since you do like it, would be nice to star the project on GitHub 😉
      I’ll take your suggestion into consideration

  • Jordi Polo, 2016-11-17, 15:04

    Hi Stefan,

    I have been using your library for some time, thank you very much, it has been very useful to me. 😉

    I’m migrating my server and I have installed the latest PHP7 realease in the new one. It seems that the library has some issues with php7.

    I will expose here the problems that I found, so if you want you can use my experience to fix them in the next library version:

    1. In the read function, line 659, a call to the regenerate_id function is made. The regenerate_id function calls “session_regenerate_id(true);” (line 433).
    The problem is that in PHP7, the session_regenerate_id function, with the delete parameter value set to true, calls the read function.

    I have fixed this problem removing the call to regenerate_id in the read function.

    2. The other problem is that the write function returns an empty string if the new session row is inserted.

    It seems that in PHP7 the return of the write function must be a boolean value. So I suggest you to return true instead of empty string when a new session row is inserted.

    I hope my experience helps you. 🙂
    And please, correct me if I’m doing any mistake or you found a better solution.


  • Dennis, 2017-02-21, 20:07

    have used and enjoy the your sessions class
    trying to convert to php 7.1 and finding several errors
    do you plan to update to php 7.1
    please let me know
    thanks, Dennis

  • Giacomo, 2017-02-22, 03:51

    Hi Stefan,
    Thank you for such a good library.
    I get some errors using PHP 7+ if user session still doesn’t exist:
    – session_regenerate_id(): Cannot call session save handler in a recursive manner in Zebra_Session.php on line 433
    – session_regenerate_id(): Session object destruction failed. ID: user (path: ) in Zebra_Session.php on line 433

    Thank you once again


Leave a Reply

Your email address will not be published
You can use <strong>, <em>, <a>, <img>, <code>
Characters are not case-sensitive