Stefan Gabos web developer extraordinaire
Zebra_Session, a wrapper for PHP’s default session handling functions, using MySQL for storageGet the latest updates on this PHP library via RSS
Latest version2.1.1released onSeptember 25, 2014
- 1. Overview
- 2. Features
- 3. Requirements
- 4. Installation
- 5. How to use
- 6. Download
- 7. Documentation
- 8. Changelog
- 9. Comments
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”).
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).
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:
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!
- 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.
<?php // 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! ?>
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:
- Zebra_cURL, a a high performance PHP cURL library
- Zebra_Database, a MySQL database wrapper written in PHP
- Zebra_Form, a jQuery augmented PHP library for creating and validating forms
- Zebra_Image, a lightweight image manipulation library written in PHP
- Zebra_Mptt, a PHP implementation of the modified preorder tree traversal algorithm
- Zebra_Pagination, a generic pagination class written in PHP
- Zebra_Session, a wrapper for PHP's default session handling functions, using MySQL for storage
Become a ninja.
Read the comprehensive documentation.
Click on a version to expand/collapse information.
- 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