PHP Class Zebra_Session

Zebra_Session implements session locking. Session locking is a way to ensure that data is correctly handled in a scenario with multiple concurrent AJAX requests. Read more about it in this excellent article by Andy Bakun called {@link http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sessions/ Race Conditions with Ajax and PHP Sessions}. This library 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! Zebra_Session 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"). Zebra_Session is was inspired by John Herren's code from the {@link http://devzone.zend.com/413/trick-out-your-session-handler/ Trick out your session handler} article and {@link http://shiflett.org/articles/the-truth-about-sessions Chris Shiflett}'s articles about PHP sessions. The code is heavily commented and generates no warnings/errors/notices when PHP's error reporting level is set to E_ALL. Visit {@link http://stefangabos.ro/php-libraries/zebra-session/} for more information. For more resources visit {@link http://stefangabos.ro/}
Afficher le fichier Open project: stefangabos/zebra_session Class Usage Examples

Méthodes publiques

Méthode Description
__construct ( resource &$link, string $security_code, integer $session_lifetime = '', boolean $lock_to_user_agent = true, boolean $lock_to_ip = false, integer $gc_probability = '', integer $gc_divisor = '', string $table_name = 'session_data', string $lock_timeout = 60 ) : void Constructor of class. Initializes the class and automatically calls {@link http://php.net/manual/en/function.session-start.php start_session()}.
_manage_flashdata ( ) Manages flashdata behind the scenes
close ( ) Custom close() function
destroy ( $session_id ) Custom destroy() function
gc ( ) Custom gc() function (garbage collector)
get_active_sessions ( ) : integer Get the number of active sessions - sessions that have not expired.
get_settings ( ) : array Queries the system for the values of session.gc_maxlifetime, session.gc_probability and session.gc_divisor and returns them as an associative array.
open ( $save_path, $session_name ) Custom open() function
read ( $session_id ) Custom read() function
regenerate_id ( ) : void Regenerates the session id.
set_flashdata ( string $name, string $value ) : void Sets a "flashdata" session variable which will only be available for the next server request, and which will be automatically deleted afterwards.
stop ( ) : void Deletes all data related to the session
write ( $session_id, $session_data ) Custom write() function

Private Methods

Méthode Description
_mysql_affected_rows ( ) Wrapper for PHP's "mysqli_affected_rows" function.
_mysql_error ( ) Wrapper for PHP's "mysqli_error" function.
_mysql_ping ( ) Wrapper for PHP's "mysqli_ping" function.
_mysql_query ( $query ) Wrapper for PHP's "mysqli_query" function.
_mysql_real_escape_string ( $string ) Wrapper for PHP's "mysqli_real_escape_string" function.

Method Details

__construct() public méthode

first, connect to a database containing the sessions table include the class require 'path/to/Zebra_Session.php'; start the session where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); By default, the cookie used by PHP to propagate session data across multiple pages ('PHPSESSID') uses the current top-level domain and subdomain in the cookie declaration. Example: www.domain.com This means that the session data is not available to other subdomains. Therefore, a session started on www.domain.com will not be available on blog.domain.com. The solution is to change the domain PHP uses when it sets the 'PHPSESSID' cookie by calling the line below *before* instantiating the Zebra_Session library. takes the domain and removes the subdomain blog.domain.com becoming .domain.com ini_set( 'session.cookie_domain', substr($_SERVER['SERVER_NAME'], strpos($_SERVER['SERVER_NAME'], '.')) ); From now on whenever PHP sets the 'PHPSESSID' cookie, the cookie will be available to all subdomains!
public __construct ( resource &$link, string $security_code, integer $session_lifetime = '', boolean $lock_to_user_agent = true, boolean $lock_to_ip = false, integer $gc_probability = '', integer $gc_divisor = '', string $table_name = 'session_data', string $lock_timeout = 60 ) : void
$link resource An object representing the connection to a MySQL Server, as returned by calling {@link http://www.php.net/manual/en/mysqli.construct.php mysqli_connect}. If you use {@link http://stefangabos.ro/php-libraries/zebra-database/ Zebra_Database} to connect to the database, you can get the connection to the MySQL server via Zebra_Database's {@link http://stefangabos.ro/wp-content/docs/Zebra_Database/Zebra_Database/Zebra_Database.html#methodget_link get_link} method. @param string $security_code The value of this argument is appended to the string created by concatenating the user's User Agent (browser) string (or an empty string if "lock_to_user_agent" is FALSE) and to the user's IP address (or an empty string if "lock_to_ip" is FALSE), before creating an MD5 hash out of it and storing it in the database. On each call this value will be generated again and compared to the value stored in the database ensuring that the session is correctly linked with the user who initiated the session thus preventing session hijacking. To prevent session hijacking, make sure you choose a string around 12 characters long containing upper- and lowercase letters, as well as digits. To simplify the process, use {@link https://www.random.org/passwords/?num=1&len=12&format=html&rnd=new this} link to generate such a random string. @param integer $session_lifetime (Optional) The number of seconds after which a session will be considered as expired. Expired sessions are cleaned up from the database whenever the garbage collection routine is run. The probability of the garbage collection routine to be executed is given by the values of $gc_probability and $gc_divisor. See below. Default is the value of session.gc_maxlifetime as set in in php.ini. Read more at {@link http://www.php.net/manual/en/session.configuration.php} To clear any confusions that may arise: in reality, session.gc_maxlifetime does not represent a session's lifetime but the number of seconds after which a session is seen as garbage and is deleted by the garbage collection routine. The PHP setting that sets a session's lifetime is session.cookie_lifetime and is usually set to "0" - indicating that a session is active until the browser/browser tab is closed. When this class is used, a session is active until the browser/browser tab is closed and/or a session has been inactive for more than the number of seconds specified by session.gc_maxlifetime. To see the actual value of session.gc_maxlifetime for your environment, use the {@link get_settings()} method. Pass an empty string to keep default value. @param boolean $lock_to_user_agent (Optional) Whether to restrict the session to the same User Agent (or browser) as when the session was first opened. The user agent check only adds minor security, since an attacker that hijacks the session cookie will most likely have the same user agent. In certain scenarios involving Internet Explorer, the browser will randomly change the user agent string from one page to the next by automatically switching into compatibility mode. So, on the first load you would have something like: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; etc... and reloading the page you would have Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; etc... So, if the situation asks for this, change this value to FALSE. Default is TRUE. @param boolean $lock_to_ip (Optional) Whether to restrict the session to the same IP as when the session was first opened. Use this with caution as many users have dynamic IP addresses which may change over time, or may come through proxies. This is mostly useful if your know that all your users come from static IPs. Default is FALSE. @param integer $gc_probability (Optional) Used in conjunction with $gc_divisor. It defines the probability that the garbage collection routine is started. The probability is expressed by the formula: $probability = $gc_probability / $gc_divisor; So, if $gc_probability is 1 and $gc_divisor is 100, it means that there is a 1% chance the the garbage collection routine will be called on each request. Default is the value of session.gc_probability as set in php.ini. Read more at {@link http://www.php.net/manual/en/session.configuration.php} To see the actual value of session.gc_probability for your environment, and the computed probability, use the {@link get_settings()} method. Pass an empty string to keep default value. @param integer $gc_divisor (Optional) Used in conjunction with $gc_probability. It defines the probability that the garbage collection routine is started. The probability is expressed by the formula: $probability = $gc_probability / $gc_divisor; So, if $gc_probability is 1 and $gc_divisor is 100, it means that there is a 1% chance the the garbage collection routine will be called on each request. Default is the value of session.gc_divisor as set in php.ini. Read more at {@link http://www.php.net/manual/en/session.configuration.php} To see the actual value of session.gc_divisor for your environment, and the computed probability, use the {@link get_settings()} method. Pass an empty string to keep default value. @param string $table_name (Optional) Name of the MySQL table used by the class. Default is session_data. @param string $lock_timeout (Optional) The maximum amount of time (in seconds) for which a lock on the session data can be kept. This must be lower than the maximum execution time of the script! Session locking is a way to ensure that data is correctly handled in a scenario with multiple concurrent AJAX requests. Read more about it at {@link http://thwartedefforts.org/2006/11/11/race-conditions-with-ajax-and-php-sessions/} Default is 60 @return void
$security_code string
$session_lifetime integer
$lock_to_user_agent boolean
$lock_to_ip boolean
$gc_probability integer
$gc_divisor integer
$table_name string
$lock_timeout string
Résultat void

_manage_flashdata() public méthode

@access private
public _manage_flashdata ( )

close() public méthode

@access private
public close ( )

destroy() public méthode

@access private
public destroy ( $session_id )

gc() public méthode

@access private
public gc ( )

get_active_sessions() public méthode

The returned value does not represent the exact number of active users as some sessions may be unused although they haven't expired. first, connect to a database containing the sessions table include the class require 'path/to/Zebra_Session.php'; start the session where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); get the (approximate) number of active sessions $active_sessions = $session->get_active_sessions();
public get_active_sessions ( ) : integer
Résultat integer Returns the number of active (not expired) sessions.

get_settings() public méthode

To view the result in a human-readable format use: include the class require 'path/to/Zebra_Session.php'; instantiate the class $session = new Zebra_Session(); get default settings print_r('
');
print_r($session->get_settings());
would output something similar to (depending on your actual settings)
Array
(
[session.gc_maxlifetime] => 1440 seconds (24 minutes)
[session.gc_probability] => 1
[session.gc_divisor] => 1000
[probability] => 0.1%
)
        
Since: 1.0.8 @return array Returns the values of session.gc_maxlifetime, session.gc_probability and session.gc_divisor as an associative array.
public get_settings ( ) : array
Résultat array

open() public méthode

@access private
public open ( $save_path, $session_name )

read() public méthode

@access private
public read ( $session_id )

regenerate_id() public méthode

Call this method whenever you do a privilege change in order to prevent session hijacking! first, connect to a database containing the sessions table include the class require 'path/to/Zebra_Session.php'; start the session where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); regenerate the session's ID $session->regenerate_id();
public regenerate_id ( ) : void
Résultat void

set_flashdata() public méthode

Typically used for informational or status messages (for example: "data has been successfully updated"). first, connect to a database containing the sessions table include the library require 'path/to/Zebra_Session.php'; start the session where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); set "myvar" which will only be available for the next server request and will be automatically deleted afterwards $session->set_flashdata('myvar', 'myval'); Flashdata session variables can be retrieved as any other session variable: if (isset($_SESSION['myvar'])) { do something here but remember that the flashdata session variable is available for a single server request after it has been set! }
public set_flashdata ( string $name, string $value ) : void
$name string The name of the session variable. @param string $value The value of the session variable. @return void
$value string
Résultat void

stop() public méthode

first, connect to a database containing the sessions table include the class require 'path/to/Zebra_Session.php'; start the session where $link is a connection link returned by mysqli_connect $session = new Zebra_Session($link, 'sEcUr1tY_c0dE'); end current session $session->stop();
Since: 1.0.1 @return void
public stop ( ) : void
Résultat void

write() public méthode

@access private
public write ( $session_id, $session_data )