cvs: pear /HTTP_Session Session.php /HTTP_Session/Session Container.php /HTTP_Session/Session/Container DB.php /HTTP_Session/docs
HTTP_Session_Example.php sessiondata.sql

From: Date: Sat, 17 Apr 2004 17:09:03 +0000
Subject: cvs: pear /HTTP_Session Session.php /HTTP_Session/Session Container.php /HTTP_Session/Session/Container DB.php /HTTP_Session/docs
HTTP_Session_Example.php sessiondata.sql
Groups: php.pear.cvs 
Request: Send a blank email to pear-cvs+get-18350@lists.php.net to get a copy of this message
neufeind Sat Apr 17 13:09:03 2004 EDT Modified files: /pear/HTTP_Session Session.php /pear/HTTP_Session/Session Container.php /pear/HTTP_Session/Session/Container DB.php /pear/HTTP_Session/docs HTTP_Session_Example.php sessiondata.sql Log: fixed line-endings (thanks to Moritz Heidkamp for pointing this out)

http://cvs.php.net/diff.php/pear/HTTP_Session/Session.php?r1=1.1&r2=1.2&ty=u Index: pear/HTTP_Session/Session.php diff -u pear/HTTP_Session/Session.php:1.1 pear/HTTP_Session/Session.php:1.2 --- pear/HTTP_Session/Session.php:1.1 Sat Oct 4 19:29:14 2003 +++ pear/HTTP_Session/Session.php Sat Apr 17 13:09:01 2004 @@ -1,571 +1,571 @@ -<?php -// -// +-----------------------------------------------------------------------+ -// | Copyright (c) 2002, Alexander Radivanovich | -// | All rights reserved. | -// | | -// | Redistribution and use in source and binary forms, with or without | -// | modification, are permitted provided that the following conditions | -// | are met: | -// | | -// | o Redistributions of source code must retain the above copyright | -// | notice, this list of conditions and the following disclaimer. | -// | o Redistributions in binary form must reproduce the above copyright | -// | notice, this list of conditions and the following disclaimer in the | -// | documentation and/or other materials provided with the distribution.| -// | o The names of the authors may not be used to endorse or promote | -// | products derived from this software without specific prior written | -// | permission. | -// | | -// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | -// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | -// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | -// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | -// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | -// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | -// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | -// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | -// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | -// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | -// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | -// | | -// +-----------------------------------------------------------------------+ -// | Author: Alexander Radivanovich <info@wwwlab.net> | -// +-----------------------------------------------------------------------+ -// - -/** @const HTTP_SESSION_STARTED - The session was started with the current request */ -define("HTTP_SESSION_STARTED", 1); -/** @const HTTP_SESSION_STARTED - No new session was started with the current request */ -define("HTTP_SESSION_CONTINUED", 2); - -/** - * Class for managing HTTP sessions - * - * Provides access to session-state values as well as session-level - * settings and lifetime management methods. - * Based on the standart PHP session handling mechanism - * it provides for you more advanced features such as - * database container, idle and expire timeouts, etc. - * - * Expample 1: - * - * <code> - * // Setting some options and detecting of a new session - * HTTP_Session::setCookieless(false); - * HTTP_Session::start('MySessionID'); - * HTTP_Session::set('variable', 'Tet string'); - * if (HTTP_Session::isNew()) { - * echo('new session was created with the current request'); - * $visitors++; // Increase visitors count - * } - * </code> - * - * Example 2: - * - * <code> - * // Using database container - * HTTP_Session::setContainer('DB'); - * HTTP_Session::start(); - * </code> - * - * Example 3: - * - * <code> - * // Setting timeouts - * HTTP_Session::start(); - * HTTP_Session::setExpire(time() + 60 * 60); // expires in one hour - * HTTP_Session::setIdle(10 * 60); // idles in ten minutes - * if (HTTP_Session::isExpired()) { - * // expired - * echo('Your session is expired!'); - * HTTP_Session::destroy(); - * } - * if (HTTP_Session::isIdle()) { - * // idle - * echo('You've been idle for too long!'); - * HTTP_Session::destroy(); - * } - * HTTP_Session::updateIdle(); - * </code> - * - * @author Alexander Radivaniovich <info@wwwlab.net> - * @package HTTP_Session - * @access public - */ -class HTTP_Session -{ - - /** - * Sets user-defined session storage functions - * - * Sets the user-defined session storage functions which are used - * for storing and retrieving data associated with a session. - * This is most useful when a storage method other than - * those supplied by PHP sessions is preferred. - * i.e. Storing the session data in a local database. - * - * @static - * @access public - * @return void - * @see session_set_save_handler() - */ - function setContainer($container, $container_options = null) - { - $container_class = 'HTTP_Session_Container_' . $container; - $container_classfile = 'HTTP/Session/Container/' . $container . '.php'; - - include_once $container_classfile; - $container = new $container_class($container_options); - - $container->set(); - } - - /** - * Initializes session data - * - * Creates a session (or resumes the current one - * based on the session id being passed - * via a GET variable or a cookie). - * You can provide your own name and/or id for a session. - * - * @static - * @access public - * @param $name string Name of a session, default is 'SessionID' - * @param $id string Id of a session which will be used - * only when the session is new - * @return void - * @see session_name() - * @see session_id() - * @see session_start() - */ - function start($name = 'SessionID', $id = null) - { - HTTP_Session::name($name); - if (is_null(HTTP_Session::detectID())) { - HTTP_Session::id($id ? $id : uniqid(dechex(rand()))); - } - session_start(); - if (!isset($_SESSION['__HTTP_Session_Info'])) { - $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_STARTED; - } else { - $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_CONTINUED; - } - } - - /** - * Writes session data and ends session - * - * Session data is usually stored after your script - * terminated without the need to call HTTP_Session::stop(), - * but as session data is locked to prevent concurrent - * writes only one script may operate on a session at any time. - * When using framesets together with sessions you will - * experience the frames loading one by one due to this - * locking. You can reduce the time needed to load all the - * frames by ending the session as soon as all changes - * to session variables are done. - * - * @static - * @access public - * @return void - * @see session_write_close() - */ - function pause() - { - session_write_close(); - } - - /** - * Frees all session variables and destroys all data - * registered to a session - * - * This method resets the $_SESSION variable and - * destroys all of the data associated - * with the current session in its storage (file or DB). - * It forces new session to be started after this method - * is called. It does not unset the session cookie. - * - * @static - * @access public - * @return void - * @see session_unset() - * @see session_destroy() - */ - function destroy() - { - session_unset(); - session_destroy(); - } - - /** - * Free all session variables - * - * @todo TODO Save expire and idle timestamps? - * @static - * @access public - * @return void - */ - function clear() - { - $info = $_SESSION['__HTTP_Session_Info']; - session_unset(); - $_SESSION['__HTTP_Session_Info'] = $info; - } - - /** - * Tries to find any session id in $_GET, $_POST or $_COOKIE - * - * @static - * @access private - * @return string Session ID (if exists) or null - */ - function detectID() - { - if (HTTP_Session::useCookies()) { - if (isset($_COOKIE[HTTP_Session::name()])) { - return $_COOKIE[HTTP_Session::name()]; - } - } else { - if (isset($_GET[HTTP_Session::name()])) { - return $_GET[HTTP_Session::name()]; - } - if (isset($_POST[HTTP_Session::name()])) { - return $_POST[HTTP_Session::name()]; - } - } - return null; - } - - /** - * Sets new name of a session - * - * @static - * @access public - * @param string $name New name of a sesion - * @return string Previous name of a session - * @see session_name() - */ - function name($name = null) - { - return isset($name) ? session_name($name) : session_name(); - } - - /** - * Sets new ID of a session - * - * @static - * @access public - * @param string $id New ID of a sesion - * @return string Previous ID of a session - * @see session_id() - */ - function id($id = null) - { - return isset($id) ? session_id($id) : session_id(); - } - - /** - * Sets the maximum expire time - * - * @static - * @access public - * @param integer $time Time in seconds - * @param bool $add Add time to current expire time or not - * @return void - */ - function setExpire($time, $add = false) - { - if ($add) { - $GLOBALS['__HTTP_Session_Expire'] += $time; - } else { - $GLOBALS['__HTTP_Session_Expire'] = $time; - } - if (!isset($_SESSION['__HTTP_Session_Expire_TS'])) { - $_SESSION['__HTTP_Session_Expire_TS'] = time(); - } - } - - /** - * Sets the maximum idle time - * - * Sets the time-out period allowed - * between requests before the session-state - * provider terminates the session. - * - * @static - * @access public - * @param integer $time Time in seconds - * @param bool $add Add time to current maximum idle time or not - * @return void - */ - function setIdle($time, $add = false) - { - if ($add) { - $GLOBALS['__HTTP_Session_Idle'] += $time; - } else { - $GLOBALS['__HTTP_Session_Idle'] = $time; - } - if (!isset($_SESSION['__HTTP_Session_Idle_TS'])) { - $_SESSION['__HTTP_Session_Idle_TS'] = time(); - } - } - - /** - * Returns the time up to the session is valid - * - * @static - * @access public - * @return integer Time when the session idles - */ - function sessionValidThru() - { - if (!isset($_SESSION['__HTTP_Session_Idle_TS']) || !isset($GLOBALS['__HTTP_Session_Idle'])) { - return 0; - } else { - return $_SESSION['__HTTP_Session_Idle_TS'] + $GLOBALS['__HTTP_Session_Idle']; - } - } - - /** - * Check if session is expired - * - * @static - * @access public - * @return boolean Obvious - */ - function isExpired() - { - if ($GLOBALS['__HTTP_Session_Expire'] > 0 && isset($_SESSION['__HTTP_Session_Expire_TS']) && - ($_SESSION['__HTTP_Session_Expire_TS'] + $GLOBALS['__HTTP_Session_Expire']) <= time()) { - return true; - } else { - return false; - } - } - - /** - * Check if session is idle - * - * @static - * @access public - * @return boolean Obvious - */ - function isIdle() - { - if ($GLOBALS['__HTTP_Session_Idle'] > 0 && isset($_SESSION['__HTTP_Session_Idle_TS']) && - ($_SESSION['__HTTP_Session_Idle_TS'] + $GLOBALS['__HTTP_Session_Idle']) <= time()) { - return true; - } else { - return false; - } - } - - /** - * Updates the idletime - * - * @static - * @access public - * @return void - */ - function updateIdle() - { - if (isset($_SESSION['__HTTP_Session_Idle_TS'])) { - $_SESSION['__HTTP_Session_Idle_TS'] = time(); - } - } - - /** - * If optional parameter is specified it indicates - * whether the module will use cookies to store - * the session id on the client side - * - * It returns the previous value of this property - * - * @static - * @access public - * @param boolean $useCookies If specified it will replace the previous value - * of this property - * @return boolean The previous value of the property - */ - function useCookies($useCookies = null) - { - $return = ini_get('session.use_cookies') ? true : false; - if (isset($useCookies)) { - ini_set('session.use_cookies', $useCookies ? 1 : 0); - } - return $return; - } - - /** - * Gets a value indicating whether the session - * was created with the current request - * - * You MUST call this method only after you have started - * the session with the HTTP_Session::start() method. - * - * @static - * @access public - * @return boolean true if the session was created - * with the current request, false otherwise - */ - function isNew() - { - // The best way to check if a session is new is to check - // for existence of a session data storage - // with the current session id, but this is impossible - // with the default PHP module wich is 'files'. - // So we need to emulate it. - return !isset($_SESSION['__HTTP_Session_Info']) || - $_SESSION['__HTTP_Session_Info'] == HTTP_SESSION_STARTED; - } - - /** - * Register variable with the current session - * - * @static - * @access public - * @param string $name Name of a global variable - * @return void - * @see session_register() - */ - function register($name) - { - session_register($name); - } - - /** - * Unregister a variable from the current session - * - * @static - * @access public - * @param string $name Name of a global variable - * @return void - * @see session_unregister() - */ - function unregister($name) - { - session_unregister($name); - } - - /** - * Returns session variable - * - * @static - * @access public - * @param string $name Name of a variable - * @param mixed $default Default value of a variable if not set - * @return mixed Value of a variable - */ - function &get($name, $default = null) - { - if (!isset($_SESSION[$name]) && isset($default)) { - $_SESSION[$name] = $default; - } - return $_SESSION[$name]; - } - - /** - * Sets session variable - * - * @access public - * @param string $name Name of a variable - * @param mixed $value Value of a variable - * @return mixed Old value of a variable - */ - function set($name, $value) - { - $return = @$_SESSION[$name]; - if (null === $value) { - unset($_SESSION[$name]); - } else { - $_SESSION[$name] = $value; - } - return $return; - } - - /** - * Returns local variable of a script - * - * Two scripts can have local variables with the same names - * - * @static - * @access public - * @param string $name Name of a variable - * @param mixed $default Default value of a variable if not set - * @return mixed Value of a local variable - */ - function &getLocal($name, $default = null) - { - $local = md5(HTTP_Session::localName()); - if (!is_array($_SESSION[$local])) { - $_SESSION[$local] = array(); - } - if (!isset($_SESSION[$local][$name]) && isset($default)) { - $_SESSION[$local][$name] = $default; - } - return $_SESSION[$local][$name]; - } - - /** - * Sets local variable of a script. - * Two scripts can have local variables with the same names. - * - * @static - * @access public - * @param string $name Name of a local variable - * @param mixed $value Value of a local variable - * @return mixed Old value of a local variable - */ - function setLocal($name, $value) - { - $local = md5(HTTP_Session::localName()); - if (!is_array($_SESSION[$local])) { - $_SESSION[$local] = array(); - } - $return = $_SESSION[$local][$name]; - if (null === $value) { - unset($_SESSION[$local][$name]); - } else { - $_SESSION[$local][$name] = $value; - } - return $return; - } - - /** - * Sets new local name - * - * @static - * @access public - * @param string New local name - * @return string Previous local name - */ - function localName($name = null) - { - $return = @$GLOBALS['__HTTP_Session_Localname']; - if (!empty($name)) { - $GLOBALS['__HTTP_Session_Localname'] = $name; - } - return $return; - } - - /** - * - * @static - * @access private - * @return void - */ - function _init() - { - // Disable auto-start of a sesion - ini_set('session.auto_start', 0); - - // Set local name equal to the current script name - HTTP_Session::localName($_SERVER['SCRIPT_NAME']); - } - -} - -HTTP_Session::_init(); - +<?php +// +// +-----------------------------------------------------------------------+ +// | Copyright (c) 2002, Alexander Radivanovich | +// | All rights reserved. | +// | | +// | Redistribution and use in source and binary forms, with or without | +// | modification, are permitted provided that the following conditions | +// | are met: | +// | | +// | o Redistributions of source code must retain the above copyright | +// | notice, this list of conditions and the following disclaimer. | +// | o Redistributions in binary form must reproduce the above copyright | +// | notice, this list of conditions and the following disclaimer in the | +// | documentation and/or other materials provided with the distribution.| +// | o The names of the authors may not be used to endorse or promote | +// | products derived from this software without specific prior written | +// | permission. | +// | | +// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | +// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | +// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | +// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | +// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | +// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | +// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | +// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | +// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | +// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | +// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +// | | +// +-----------------------------------------------------------------------+ +// | Author: Alexander Radivanovich <info@wwwlab.net> | +// +-----------------------------------------------------------------------+ +// + +/** @const HTTP_SESSION_STARTED - The session was started with the current request */ +define("HTTP_SESSION_STARTED", 1); +/** @const HTTP_SESSION_STARTED - No new session was started with the current request */ +define("HTTP_SESSION_CONTINUED", 2); + +/** + * Class for managing HTTP sessions + * + * Provides access to session-state values as well as session-level + * settings and lifetime management methods. + * Based on the standart PHP session handling mechanism + * it provides for you more advanced features such as + * database container, idle and expire timeouts, etc. + * + * Expample 1: + * + * <code> + * // Setting some options and detecting of a new session + * HTTP_Session::setCookieless(false); + * HTTP_Session::start('MySessionID'); + * HTTP_Session::set('variable', 'Tet string'); + * if (HTTP_Session::isNew()) { + * echo('new session was created with the current request'); + * $visitors++; // Increase visitors count + * } + * </code> + * + * Example 2: + * + * <code> + * // Using database container + * HTTP_Session::setContainer('DB'); + * HTTP_Session::start(); + * </code> + * + * Example 3: + * + * <code> + * // Setting timeouts + * HTTP_Session::start(); + * HTTP_Session::setExpire(time() + 60 * 60); // expires in one hour + * HTTP_Session::setIdle(10 * 60); // idles in ten minutes + * if (HTTP_Session::isExpired()) { + * // expired + * echo('Your session is expired!'); + * HTTP_Session::destroy(); + * } + * if (HTTP_Session::isIdle()) { + * // idle + * echo('You've been idle for too long!'); + * HTTP_Session::destroy(); + * } + * HTTP_Session::updateIdle(); + * </code> + * + * @author Alexander Radivaniovich <info@wwwlab.net> + * @package HTTP_Session + * @access public + */ +class HTTP_Session +{ + + /** + * Sets user-defined session storage functions + * + * Sets the user-defined session storage functions which are used + * for storing and retrieving data associated with a session. + * This is most useful when a storage method other than + * those supplied by PHP sessions is preferred. + * i.e. Storing the session data in a local database. + * + * @static + * @access public + * @return void + * @see session_set_save_handler() + */ + function setContainer($container, $container_options = null) + { + $container_class = 'HTTP_Session_Container_' . $container; + $container_classfile = 'HTTP/Session/Container/' . $container . '.php'; + + include_once $container_classfile; + $container = new $container_class($container_options); + + $container->set(); + } + + /** + * Initializes session data + * + * Creates a session (or resumes the current one + * based on the session id being passed + * via a GET variable or a cookie). + * You can provide your own name and/or id for a session. + * + * @static + * @access public + * @param $name string Name of a session, default is 'SessionID' + * @param $id string Id of a session which will be used + * only when the session is new + * @return void + * @see session_name() + * @see session_id() + * @see session_start() + */ + function start($name = 'SessionID', $id = null) + { + HTTP_Session::name($name); + if (is_null(HTTP_Session::detectID())) { + HTTP_Session::id($id ? $id : uniqid(dechex(rand()))); + } + session_start(); + if (!isset($_SESSION['__HTTP_Session_Info'])) { + $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_STARTED; + } else { + $_SESSION['__HTTP_Session_Info'] = HTTP_SESSION_CONTINUED; + } + } + + /** + * Writes session data and ends session + * + * Session data is usually stored after your script + * terminated without the need to call HTTP_Session::stop(), + * but as session data is locked to prevent concurrent + * writes only one script may operate on a session at any time. + * When using framesets together with sessions you will + * experience the frames loading one by one due to this + * locking. You can reduce the time needed to load all the + * frames by ending the session as soon as all changes + * to session variables are done. + * + * @static + * @access public + * @return void + * @see session_write_close() + */ + function pause() + { + session_write_close(); + } + + /** + * Frees all session variables and destroys all data + * registered to a session + * + * This method resets the $_SESSION variable and + * destroys all of the data associated + * with the current session in its storage (file or DB). + * It forces new session to be started after this method + * is called. It does not unset the session cookie. + * + * @static + * @access public + * @return void + * @see session_unset() + * @see session_destroy() + */ + function destroy() + { + session_unset(); + session_destroy(); + } + + /** + * Free all session variables + * + * @todo TODO Save expire and idle timestamps? + * @static + * @access public + * @return void + */ + function clear() + { + $info = $_SESSION['__HTTP_Session_Info']; + session_unset(); + $_SESSION['__HTTP_Session_Info'] = $info; + } + + /** + * Tries to find any session id in $_GET, $_POST or $_COOKIE + * + * @static + * @access private + * @return string Session ID (if exists) or null + */ + function detectID() + { + if (HTTP_Session::useCookies()) { + if (isset($_COOKIE[HTTP_Session::name()])) { + return $_COOKIE[HTTP_Session::name()]; + } + } else { + if (isset($_GET[HTTP_Session::name()])) { + return $_GET[HTTP_Session::name()]; + } + if (isset($_POST[HTTP_Session::name()])) { + return $_POST[HTTP_Session::name()]; + } + } + return null; + } + + /** + * Sets new name of a session + * + * @static + * @access public + * @param string $name New name of a sesion + * @return string Previous name of a session + * @see session_name() + */ + function name($name = null) + { + return isset($name) ? session_name($name) : session_name(); + } + + /** + * Sets new ID of a session + * + * @static + * @access public + * @param string $id New ID of a sesion + * @return string Previous ID of a session + * @see session_id() + */ + function id($id = null) + { + return isset($id) ? session_id($id) : session_id(); + } + + /** + * Sets the maximum expire time + * + * @static + * @access public + * @param integer $time Time in seconds + * @param bool $add Add time to current expire time or not + * @return void + */ + function setExpire($time, $add = false) + { + if ($add) { + $GLOBALS['__HTTP_Session_Expire'] += $time; + } else { + $GLOBALS['__HTTP_Session_Expire'] = $time; + } + if (!isset($_SESSION['__HTTP_Session_Expire_TS'])) { + $_SESSION['__HTTP_Session_Expire_TS'] = time(); + } + } + + /** + * Sets the maximum idle time + * + * Sets the time-out period allowed + * between requests before the session-state + * provider terminates the session. + * + * @static + * @access public + * @param integer $time Time in seconds + * @param bool $add Add time to current maximum idle time or not + * @return void + */ + function setIdle($time, $add = false) + { + if ($add) { + $GLOBALS['__HTTP_Session_Idle'] += $time; + } else { + $GLOBALS['__HTTP_Session_Idle'] = $time; + } + if (!isset($_SESSION['__HTTP_Session_Idle_TS'])) { + $_SESSION['__HTTP_Session_Idle_TS'] = time(); + } + } + + /** + * Returns the time up to the session is valid + * + * @static + * @access public + * @return integer Time when the session idles + */ + function sessionValidThru() + { + if (!isset($_SESSION['__HTTP_Session_Idle_TS']) || !isset($GLOBALS['__HTTP_Session_Idle'])) { + return 0; + } else { + return $_SESSION['__HTTP_Session_Idle_TS'] + $GLOBALS['__HTTP_Session_Idle']; + } + } + + /** + * Check if session is expired + * + * @static + * @access public + * @return boolean Obvious + */ + function isExpired() + { + if ($GLOBALS['__HTTP_Session_Expire'] > 0 && isset($_SESSION['__HTTP_Session_Expire_TS']) && + ($_SESSION['__HTTP_Session_Expire_TS'] + $GLOBALS['__HTTP_Session_Expire']) <= time()) { + return true; + } else { + return false; + } + } + + /** + * Check if session is idle + * + * @static + * @access public + * @return boolean Obvious + */ + function isIdle() + { + if ($GLOBALS['__HTTP_Session_Idle'] > 0 && isset($_SESSION['__HTTP_Session_Idle_TS']) && + ($_SESSION['__HTTP_Session_Idle_TS'] + $GLOBALS['__HTTP_Session_Idle']) <= time()) { + return true; + } else { + return false; + } + } + + /** + * Updates the idletime + * + * @static + * @access public + * @return void + */ + function updateIdle() + { + if (isset($_SESSION['__HTTP_Session_Idle_TS'])) { + $_SESSION['__HTTP_Session_Idle_TS'] = time(); + } + } + + /** + * If optional parameter is specified it indicates + * whether the module will use cookies to store + * the session id on the client side + * + * It returns the previous value of this property + * + * @static + * @access public + * @param boolean $useCookies If specified it will replace the previous value + * of this property + * @return boolean The previous value of the property + */ + function useCookies($useCookies = null) + { + $return = ini_get('session.use_cookies') ? true : false; + if (isset($useCookies)) { + ini_set('session.use_cookies', $useCookies ? 1 : 0); + } + return $return; + } + + /** + * Gets a value indicating whether the session + * was created with the current request + * + * You MUST call this method only after you have started + * the session with the HTTP_Session::start() method. + * + * @static + * @access public + * @return boolean true if the session was created + * with the current request, false otherwise + */ + function isNew() + { + // The best way to check if a session is new is to check + // for existence of a session data storage + // with the current session id, but this is impossible + // with the default PHP module wich is 'files'. + // So we need to emulate it. + return !isset($_SESSION['__HTTP_Session_Info']) || + $_SESSION['__HTTP_Session_Info'] == HTTP_SESSION_STARTED; + } + + /** + * Register variable with the current session + * + * @static + * @access public + * @param string $name Name of a global variable + * @return void + * @see session_register() + */ + function register($name) + { + session_register($name); + } + + /** + * Unregister a variable from the current session + * + * @static + * @access public + * @param string $name Name of a global variable + * @return void + * @see session_unregister() + */ + function unregister($name) + { + session_unregister($name); + } + + /** + * Returns session variable + * + * @static + * @access public + * @param string $name Name of a variable + * @param mixed $default Default value of a variable if not set + * @return mixed Value of a variable + */ + function &get($name, $default = null) + { + if (!isset($_SESSION[$name]) && isset($default)) { + $_SESSION[$name] = $default; + } + return $_SESSION[$name]; + } + + /** + * Sets session variable + * + * @access public + * @param string $name Name of a variable + * @param mixed $value Value of a variable + * @return mixed Old value of a variable + */ + function set($name, $value) + { + $return = @$_SESSION[$name]; + if (null === $value) { + unset($_SESSION[$name]); + } else { + $_SESSION[$name] = $value; + } + return $return; + } + + /** + * Returns local variable of a script + * + * Two scripts can have local variables with the same names + * + * @static + * @access public + * @param string $name Name of a variable + * @param mixed $default Default value of a variable if not set + * @return mixed Value of a local variable + */ + function &getLocal($name, $default = null) + { + $local = md5(HTTP_Session::localName()); + if (!is_array($_SESSION[$local])) { + $_SESSION[$local] = array(); + } + if (!isset($_SESSION[$local][$name]) && isset($default)) { + $_SESSION[$local][$name] = $default; + } + return $_SESSION[$local][$name]; + } + + /** + * Sets local variable of a script. + * Two scripts can have local variables with the same names. + * + * @static + * @access public + * @param string $name Name of a local variable + * @param mixed $value Value of a local variable + * @return mixed Old value of a local variable + */ + function setLocal($name, $value) + { + $local = md5(HTTP_Session::localName()); + if (!is_array($_SESSION[$local])) { + $_SESSION[$local] = array(); + } + $return = $_SESSION[$local][$name]; + if (null === $value) { + unset($_SESSION[$local][$name]); + } else { + $_SESSION[$local][$name] = $value; + } + return $return; + } + + /** + * Sets new local name + * + * @static + * @access public + * @param string New local name + * @return string Previous local name + */ + function localName($name = null) + { + $return = @$GLOBALS['__HTTP_Session_Localname']; + if (!empty($name)) { + $GLOBALS['__HTTP_Session_Localname'] = $name; + } + return $return; + } + + /** + * + * @static + * @access private + * @return void + */ + function _init() + { + // Disable auto-start of a sesion + ini_set('session.auto_start', 0); + + // Set local name equal to the current script name + HTTP_Session::localName($_SERVER['SCRIPT_NAME']); + } + +} + +HTTP_Session::_init(); + ?> \ No newline at end of file http://cvs.php.net/diff.php/pear/HTTP_Session/Session/Container.php?r1=1.1&r2=1.2&ty=u Index: pear/HTTP_Session/Session/Container.php diff -u pear/HTTP_Session/Session/Container.php:1.1 pear/HTTP_Session/Session/Container.php:1.2 --- pear/HTTP_Session/Session/Container.php:1.1 Sat Oct 4 19:29:16 2003 +++ pear/HTTP_Session/Session/Container.php Sat Apr 17 13:09:02 2004 @@ -1,220 +1,220 @@ -<?php -// -// +-----------------------------------------------------------------------+ -// | Copyright (c) 2002, Alexander Radivanovich | -// | All rights reserved. | -// | | -// | Redistribution and use in source and binary forms, with or without | -// | modification, are permitted provided that the following conditions | -// | are met: | -// | | -// | o Redistributions of source code must retain the above copyright | -// | notice, this list of conditions and the following disclaimer. | -// | o Redistributions in binary form must reproduce the above copyright | -// | notice, this list of conditions and the following disclaimer in the | -// | documentation and/or other materials provided with the distribution.| -// | o The names of the authors may not be used to endorse or promote | -// | products derived from this software without specific prior written | -// | permission. | -// | | -// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | -// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | -// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | -// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | -// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | -// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | -// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | -// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | -// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | -// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | -// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | -// | | -// +-----------------------------------------------------------------------+ -// | Author: Alexander Radivanovich <info@wwwlab.net> | -// +-----------------------------------------------------------------------+ -// - -/** - * Container class for storing session data data - * - * @author Alexander Radivaniovich <info@wwwlab.net> - * @package HTTP_Session - * @access public - */ -class HTTP_Session_Container -{ - - /** - * Additional options for the container object - * - * @var array - * @access private - */ - var $options = array(); - - /** - * Constrtuctor method - * - * @access public - * @param array $options Additional options for the container object - * @return void - */ - function HTTP_Session_Container($options = null) - { - $this->_setDefaults(); - if (is_array($options)) { - $this->_parseOptions(); - } - } - - /** - * Set some default options - * - * @access private - */ - function _setDefaults() - { - } - - /** - * Parse options passed to the container class - * - * @access private - * @param array Options - */ - function _parseOptions($options) - { - foreach ($options as $option => $value) { - if (in_array($option, array_keys($this->options))) { - $this->options[$option] = $value; - } - } - } - - /** - * This function is called by the session - * handler to initialize things - * - * @access public - */ - function open($save_path, $session_name) - { - return true; - } - - /** - * This function is called when the page is finished - * executing and the session handler needs to close things off - * - * Has to be overwritten by each container class - * - * @access public - */ - function close() - { - return true; - } - - /** - * This function is called by the session handler - * to read the data associated with a given session ID. - * This function must retrieve and return the session data - * for the session identified by $id. - * - * Has to be overwritten by each container class - * - * @access public - * @param mixed $id ID of the session - * @return mixed The data associated with a given session ID - */ - function read($id) - { - return ''; - } - - /** - * This function is called when the session handler - * has session data to save, which usually happens - * at the end of your script - * - * Has to be overwritten by each container class - * - * @access public - * @param mixed $id ID of the session - * @param mixed $data The data associated with a given session ID - * @return boolean Obvious - */ - function write($id, $data) - { - return true; - } - - /** - * This function is called when a session is destroyed. - * It is responsible for deleting the session and cleaning things up. - * - * Has to be overwritten by each container class - * - * @access public - * @param mixed $id ID of the session - * @return boolean Obvious - */ - function destroy($id) - { - return true; - } - - /** - * This function is responsible for garbage collection. - * In the case of session handling, it is responsible - * for deleting old, stale sessions that are hanging around. - * The session handler will call this every now and then. - * - * Has to be overwritten by each container class - * - * @access public - * @param integer $maxlifetime ??? - * @return boolean Obvious - */ - function gc($maxlifetime) - { - return true; - } - - /** - * Set session save handler - * - * @access public - * @return void - */ - function set() - { - $GLOBALS['HTTP_Session_Container'] =& $this; - session_module_name('user'); - session_set_save_handler( - 'HTTP_Session_Open', - 'HTTP_Session_Close', - 'HTTP_Session_Read', - 'HTTP_Session_Write', - 'HTTP_Session_Destroy', - 'HTTP_Session_GC' - ); - } - -} - -// Delegate function calls to the object's methods -/** @ignore */ -function HTTP_Session_Open($save_path, $session_name) { return $GLOBALS['HTTP_Session_Container']->open($save_path, $session_name); } -/** @ignore */ -function HTTP_Session_Close() { return $GLOBALS['HTTP_Session_Container']->close(); } -/** @ignore */ -function HTTP_Session_Read($id) { return $GLOBALS['HTTP_Session_Container']->read($id); } -/** @ignore */ -function HTTP_Session_Write($id, $data) { return $GLOBALS['HTTP_Session_Container']->write($id, $data); } -/** @ignore */ -function HTTP_Session_Destroy($id) { return $GLOBALS['HTTP_Session_Container']->destroy($id); } -/** @ignore */ -function HTTP_Session_GC($maxlifetime) { return $GLOBALS['HTTP_Session_Container']->gc($maxlifetime); } - +<?php +// +// +-----------------------------------------------------------------------+ +// | Copyright (c) 2002, Alexander Radivanovich | +// | All rights reserved. | +// | | +// | Redistribution and use in source and binary forms, with or without | +// | modification, are permitted provided that the following conditions | +// | are met: | +// | | +// | o Redistributions of source code must retain the above copyright | +// | notice, this list of conditions and the following disclaimer. | +// | o Redistributions in binary form must reproduce the above copyright | +// | notice, this list of conditions and the following disclaimer in the | +// | documentation and/or other materials provided with the distribution.| +// | o The names of the authors may not be used to endorse or promote | +// | products derived from this software without specific prior written | +// | permission. | +// | | +// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | +// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | +// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | +// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | +// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | +// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | +// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | +// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | +// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | +// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | +// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +// | | +// +-----------------------------------------------------------------------+ +// | Author: Alexander Radivanovich <info@wwwlab.net> | +// +-----------------------------------------------------------------------+ +// + +/** + * Container class for storing session data data + * + * @author Alexander Radivaniovich <info@wwwlab.net> + * @package HTTP_Session + * @access public + */ +class HTTP_Session_Container +{ + + /** + * Additional options for the container object + * + * @var array + * @access private + */ + var $options = array(); + + /** + * Constrtuctor method + * + * @access public + * @param array $options Additional options for the container object + * @return void + */ + function HTTP_Session_Container($options = null) + { + $this->_setDefaults(); + if (is_array($options)) { + $this->_parseOptions(); + } + } + + /** + * Set some default options + * + * @access private + */ + function _setDefaults() + { + } + + /** + * Parse options passed to the container class + * + * @access private + * @param array Options + */ + function _parseOptions($options) + { + foreach ($options as $option => $value) { + if (in_array($option, array_keys($this->options))) { + $this->options[$option] = $value; + } + } + } + + /** + * This function is called by the session + * handler to initialize things + * + * @access public + */ + function open($save_path, $session_name) + { + return true; + } + + /** + * This function is called when the page is finished + * executing and the session handler needs to close things off + * + * Has to be overwritten by each container class + * + * @access public + */ + function close() + { + return true; + } + + /** + * This function is called by the session handler + * to read the data associated with a given session ID. + * This function must retrieve and return the session data + * for the session identified by $id. + * + * Has to be overwritten by each container class + * + * @access public + * @param mixed $id ID of the session + * @return mixed The data associated with a given session ID + */ + function read($id) + { + return ''; + } + + /** + * This function is called when the session handler + * has session data to save, which usually happens + * at the end of your script + * + * Has to be overwritten by each container class + * + * @access public + * @param mixed $id ID of the session + * @param mixed $data The data associated with a given session ID + * @return boolean Obvious + */ + function write($id, $data) + { + return true; + } + + /** + * This function is called when a session is destroyed. + * It is responsible for deleting the session and cleaning things up. + * + * Has to be overwritten by each container class + * + * @access public + * @param mixed $id ID of the session + * @return boolean Obvious + */ + function destroy($id) + { + return true; + } + + /** + * This function is responsible for garbage collection. + * In the case of session handling, it is responsible + * for deleting old, stale sessions that are hanging around. + * The session handler will call this every now and then. + * + * Has to be overwritten by each container class + * + * @access public + * @param integer $maxlifetime ??? + * @return boolean Obvious + */ + function gc($maxlifetime) + { + return true; + } + + /** + * Set session save handler + * + * @access public + * @return void + */ + function set() + { + $GLOBALS['HTTP_Session_Container'] =& $this; + session_module_name('user'); + session_set_save_handler( + 'HTTP_Session_Open', + 'HTTP_Session_Close', + 'HTTP_Session_Read', + 'HTTP_Session_Write', + 'HTTP_Session_Destroy', + 'HTTP_Session_GC' + ); + } + +} + +// Delegate function calls to the object's methods +/** @ignore */ +function HTTP_Session_Open($save_path, $session_name) { return $GLOBALS['HTTP_Session_Container']->open($save_path, $session_name); } +/** @ignore */ +function HTTP_Session_Close() { return $GLOBALS['HTTP_Session_Container']->close(); } +/** @ignore */ +function HTTP_Session_Read($id) { return $GLOBALS['HTTP_Session_Container']->read($id); } +/** @ignore */ +function HTTP_Session_Write($id, $data) { return $GLOBALS['HTTP_Session_Container']->write($id, $data); } +/** @ignore */ +function HTTP_Session_Destroy($id) { return $GLOBALS['HTTP_Session_Container']->destroy($id); } +/** @ignore */ +function HTTP_Session_GC($maxlifetime) { return $GLOBALS['HTTP_Session_Container']->gc($maxlifetime); } + ?> \ No newline at end of file http://cvs.php.net/diff.php/pear/HTTP_Session/Session/Container/DB.php?r1=1.1&r2=1.2&ty=u Index: pear/HTTP_Session/Session/Container/DB.php diff -u pear/HTTP_Session/Session/Container/DB.php:1.1 pear/HTTP_Session/Session/Container/DB.php:1.2 --- pear/HTTP_Session/Session/Container/DB.php:1.1 Sat Oct 4 19:29:55 2003 +++ pear/HTTP_Session/Session/Container/DB.php Sat Apr 17 13:09:02 2004 @@ -1,301 +1,301 @@ -<?php -// -// +-----------------------------------------------------------------------+ -// | Copyright (c) 2002, Alexander Radivanovich | -// | All rights reserved. | -// | | -// | Redistribution and use in source and binary forms, with or without | -// | modification, are permitted provided that the following conditions | -// | are met: | -// | | -// | o Redistributions of source code must retain the above copyright | -// | notice, this list of conditions and the following disclaimer. | -// | o Redistributions in binary form must reproduce the above copyright | -// | notice, this list of conditions and the following disclaimer in the | -// | documentation and/or other materials provided with the distribution.| -// | o The names of the authors may not be used to endorse or promote | -// | products derived from this software without specific prior written | -// | permission. | -// | | -// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | -// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | -// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | -// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | -// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | -// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | -// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | -// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | -// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | -// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | -// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | -// | | -// +-----------------------------------------------------------------------+ -// | Author: Alexander Radivanovich <info@wwwlab.net> | -// +-----------------------------------------------------------------------+ -// - -require_once "HTTP/Session/Container.php"; -require_once "DB.php"; - -/** - * Database container for session data - * - * Create the following table to store session data - * <code> - * CREATE TABLE `sessiondata` ( - * `id` CHAR(32) NOT NULL, - * `expiry` INT UNSIGNED NOT NULL DEFAULT 0, - * `data` TEXT NOT NULL, - * PRIMARY KEY (`id`) - * ); - * </code> - * - * @author Alexander Radivanovich <info@wwwlab.net> - * @package HTTP_Session - * @access public - */ -class HTTP_Session_Container_DB extends HTTP_Session_Container -{ - - /** - * DB connection object - * - * @var object DB - * @access private - */ - var $db = null; - - /** - * Session data cache id - * - * @var mixed - * @access private - */ - var $crc = false; - - /** - * Constrtuctor method - * - * $options is an array with the options.<br> - * The options are: - * <ul> - * <li>'dsn' - The DSN string</li> - * <li>'table' - Table with session data, default is 'sessiondata'</li> - * <li>'autooptimize' - Boolean, 'true' to optimize - * the table on garbage collection, default is 'false'.</li> - * </ul> - * - * @access public - * @param array $options The options - * @return void - */ - function HTTP_Session_Container_DB($options) - { - $this->_setDefaults(); - if (is_array($options)) { - $this->_parseOptions($options); - } else { - $this->options['dsn'] = $options; - } - } - - /** - * Connect to database by using the given DSN string - * - * @access private - * @param string DSN string - * @return mixed Object on error, otherwise bool - */ - function _connect($dsn) - { - if (is_string($dsn)) { - $this->db = DB::connect($dsn); - } else if (is_object($dsn) && is_a($dsn, "db_common")) { - $this->db = $dsn; - } else if (is_object($dsn) && DB::isError($dsn)) { - return new DB_Error($dsn->code, PEAR_ERROR_DIE); - } else { - return new PEAR_Error("The given dsn was not valid in file " . __FILE__ . " at line " . __LINE__, - 41, - PEAR_ERROR_RETURN, - null, - null - ); - - } - - if (DB::isError($this->db)) { - return new DB_Error($this->db->code, PEAR_ERROR_DIE); - } - - return true; - } - - /** - * Set some default options - * - * @access private - */ - function _setDefaults() - { - $this->options['dsn'] = null; - $this->options['table'] = 'sessiondata'; - $this->options['autooptimize'] = false; - } - - /** - * Establish connection to a database - * - */ - function open($save_path, $session_name) - { - if (DB::isError($this->_connect($this->options['dsn']))) { - return false; - } else { - return true; - } - } - - /** - * Free resources - * - */ - function close() - { - return true; - } - - /** - * Read session data - * - */ - function read($id) - { - $query = sprintf("SELECT data FROM %s WHERE id = %s AND expiry >= %d", - $this->options['table'], - $this->db->quote(md5($id)), - time() - ); - $result = $this->db->getOne($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - $this->crc = strlen($result) . crc32($result); - return $result; - } - - /** - * Write session data - * - */ - function write($id, $data) - { - if ((false !== $this->crc) && ($this->crc === strlen($data) . crc32($data))) { - // $_SESSION hasn't been touched, no need to update the blob column - $query = sprintf("UPDATE %s SET expiry = %d WHERE id = %s AND expiry >= %d", - $this->options['table'], - time() + ini_get('session.gc_maxlifetime'), - $this->db->quote(md5($id)), - time() - ); - } else { - // Check if table row already exists - $query = sprintf("SELECT COUNT(id) FROM %s WHERE id = %s", - $this->options['table'], - $this->db->quote(md5($id)) - ); - $result = $this->db->getOne($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - if (0 == intval($result)) { - // Insert new row into table - $query = sprintf("INSERT INTO %s (id, expiry, data) VALUES (%s, %d, %s)", - $this->options['table'], - $this->db->quote(md5($id)), - time() + ini_get('session.gc_maxlifetime'), - $this->db->quote($data) - ); - } else { - // Update existing row - $query = sprintf("UPDATE %s SET expiry = %d, data = %s WHERE id = %s AND expiry >= %d", - $this->options['table'], - time() + ini_get('session.gc_maxlifetime'), - $this->db->quote($data), - $this->db->quote(md5($id)), - time() - ); - } - } - $result = $this->db->query($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - - return true; - } - - /** - * Destroy session data - * - */ - function destroy($id) - { - $query = sprintf("DELETE FROM %s WHERE id = %s", - $this->options['table'], - $this->db->quote(md5($id)) - ); - $result = $this->db->query($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - - return true; - } - - /** - * Garbage collection - * - */ - function gc($maxlifetime) - { - $query = sprintf("DELETE FROM %s WHERE expiry < %d", - $this->options['table'], - time() - ); - $result = $this->db->query($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - if ($this->options['autooptimize']) { - switch($this->db->type) { - case 'mysql': - $query = sprintf("OPTIMIZE TABLE %s", $this->options['table']); - break; - case 'pgsql': - $query = sprintf("VACUUM %s", $this->options['table']); - break; - default: - $query = null; - break; - } - if (isset($query)) { - $result = $this->db->query($query); - if (DB::isError($result)) { - new DB_Error($result->code, PEAR_ERROR_DIE); - return false; - } - } - } - - return true; - } - -} - +<?php +// +// +-----------------------------------------------------------------------+ +// | Copyright (c) 2002, Alexander Radivanovich | +// | All rights reserved. | +// | | +// | Redistribution and use in source and binary forms, with or without | +// | modification, are permitted provided that the following conditions | +// | are met: | +// | | +// | o Redistributions of source code must retain the above copyright | +// | notice, this list of conditions and the following disclaimer. | +// | o Redistributions in binary form must reproduce the above copyright | +// | notice, this list of conditions and the following disclaimer in the | +// | documentation and/or other materials provided with the distribution.| +// | o The names of the authors may not be used to endorse or promote | +// | products derived from this software without specific prior written | +// | permission. | +// | | +// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | +// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | +// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | +// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | +// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | +// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | +// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | +// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | +// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | +// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | +// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +// | | +// +-----------------------------------------------------------------------+ +// | Author: Alexander Radivanovich <info@wwwlab.net> | +// +-----------------------------------------------------------------------+ +// + +require_once "HTTP/Session/Container.php"; +require_once "DB.php"; + +/** + * Database container for session data + * + * Create the following table to store session data + * <code> + * CREATE TABLE `sessiondata` ( + * `id` CHAR(32) NOT NULL, + * `expiry` INT UNSIGNED NOT NULL DEFAULT 0, + * `data` TEXT NOT NULL, + * PRIMARY KEY (`id`) + * ); + * </code> + * + * @author Alexander Radivanovich <info@wwwlab.net> + * @package HTTP_Session + * @access public + */ +class HTTP_Session_Container_DB extends HTTP_Session_Container +{ + + /** + * DB connection object + * + * @var object DB + * @access private + */ + var $db = null; + + /** + * Session data cache id + * + * @var mixed + * @access private + */ + var $crc = false; + + /** + * Constrtuctor method + * + * $options is an array with the options.<br> + * The options are: + * <ul> + * <li>'dsn' - The DSN string</li> + * <li>'table' - Table with session data, default is 'sessiondata'</li> + * <li>'autooptimize' - Boolean, 'true' to optimize + * the table on garbage collection, default is 'false'.</li> + * </ul> + * + * @access public + * @param array $options The options + * @return void + */ + function HTTP_Session_Container_DB($options) + { + $this->_setDefaults(); + if (is_array($options)) { + $this->_parseOptions($options); + } else { + $this->options['dsn'] = $options; + } + } + + /** + * Connect to database by using the given DSN string + * + * @access private + * @param string DSN string + * @return mixed Object on error, otherwise bool + */ + function _connect($dsn) + { + if (is_string($dsn)) { + $this->db = DB::connect($dsn); + } else if (is_object($dsn) && is_a($dsn, "db_common")) { + $this->db = $dsn; + } else if (is_object($dsn) && DB::isError($dsn)) { + return new DB_Error($dsn->code, PEAR_ERROR_DIE); + } else { + return new PEAR_Error("The given dsn was not valid in file " . __FILE__ . " at line " . __LINE__, + 41, + PEAR_ERROR_RETURN, + null, + null + ); + + } + + if (DB::isError($this->db)) { + return new DB_Error($this->db->code, PEAR_ERROR_DIE); + } + + return true; + } + + /** + * Set some default options + * + * @access private + */ + function _setDefaults() + { + $this->options['dsn'] = null; + $this->options['table'] = 'sessiondata'; + $this->options['autooptimize'] = false; + } + + /** + * Establish connection to a database + * + */ + function open($save_path, $session_name) + { + if (DB::isError($this->_connect($this->options['dsn']))) { + return false; + } else { + return true; + } + } + + /** + * Free resources + * + */ + function close() + { + return true; + } + + /** + * Read session data + * + */ + function read($id) + { + $query = sprintf("SELECT data FROM %s WHERE id = %s AND expiry >= %d", + $this->options['table'], + $this->db->quote(md5($id)), + time() + ); + $result = $this->db->getOne($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + $this->crc = strlen($result) . crc32($result); + return $result; + } + + /** + * Write session data + * + */ + function write($id, $data) + { + if ((false !== $this->crc) && ($this->crc === strlen($data) . crc32($data))) { + // $_SESSION hasn't been touched, no need to update the blob column + $query = sprintf("UPDATE %s SET expiry = %d WHERE id = %s AND expiry >= %d", + $this->options['table'], + time() + ini_get('session.gc_maxlifetime'), + $this->db->quote(md5($id)), + time() + ); + } else { + // Check if table row already exists + $query = sprintf("SELECT COUNT(id) FROM %s WHERE id = %s", + $this->options['table'], + $this->db->quote(md5($id)) + ); + $result = $this->db->getOne($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + if (0 == intval($result)) { + // Insert new row into table + $query = sprintf("INSERT INTO %s (id, expiry, data) VALUES (%s, %d, %s)", + $this->options['table'], + $this->db->quote(md5($id)), + time() + ini_get('session.gc_maxlifetime'), + $this->db->quote($data) + ); + } else { + // Update existing row + $query = sprintf("UPDATE %s SET expiry = %d, data = %s WHERE id = %s AND expiry >= %d", + $this->options['table'], + time() + ini_get('session.gc_maxlifetime'), + $this->db->quote($data), + $this->db->quote(md5($id)), + time() + ); + } + } + $result = $this->db->query($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + + return true; + } + + /** + * Destroy session data + * + */ + function destroy($id) + { + $query = sprintf("DELETE FROM %s WHERE id = %s", + $this->options['table'], + $this->db->quote(md5($id)) + ); + $result = $this->db->query($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + + return true; + } + + /** + * Garbage collection + * + */ + function gc($maxlifetime) + { + $query = sprintf("DELETE FROM %s WHERE expiry < %d", + $this->options['table'], + time() + ); + $result = $this->db->query($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + if ($this->options['autooptimize']) { + switch($this->db->type) { + case 'mysql': + $query = sprintf("OPTIMIZE TABLE %s", $this->options['table']); + break; + case 'pgsql': + $query = sprintf("VACUUM %s", $this->options['table']); + break; + default: + $query = null; + break; + } + if (isset($query)) { + $result = $this->db->query($query); + if (DB::isError($result)) { + new DB_Error($result->code, PEAR_ERROR_DIE); + return false; + } + } + } + + return true; + } + +} + ?> \ No newline at end of file http://cvs.php.net/diff.php/pear/HTTP_Session/docs/HTTP_Session_Example.php?r1=1.1&r2=1.2&ty=u Index: pear/HTTP_Session/docs/HTTP_Session_Example.php diff -u pear/HTTP_Session/docs/HTTP_Session_Example.php:1.1 pear/HTTP_Session/docs/HTTP_Session_Example.php:1.2 --- pear/HTTP_Session/docs/HTTP_Session_Example.php:1.1 Sat Oct 4 19:29:17 2003 +++ pear/HTTP_Session/docs/HTTP_Session_Example.php Sat Apr 17 13:09:02 2004 @@ -1,136 +1,136 @@ -<?php -// -// +-----------------------------------------------------------------------+ -// | Copyright (c) 2002, Alexander Radivanovich | -// | All rights reserved. | -// | | -// | Redistribution and use in source and binary forms, with or without | -// | modification, are permitted provided that the following conditions | -// | are met: | -// | | -// | o Redistributions of source code must retain the above copyright | -// | notice, this list of conditions and the following disclaimer. | -// | o Redistributions in binary form must reproduce the above copyright | -// | notice, this list of conditions and the following disclaimer in the | -// | documentation and/or other materials provided with the distribution.| -// | o The names of the authors may not be used to endorse or promote | -// | products derived from this software without specific prior written | -// | permission. | -// | | -// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | -// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | -// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | -// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | -// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | -// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | -// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | -// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | -// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | -// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | -// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | -// | | -// +-----------------------------------------------------------------------+ -// | Author: Alexander Radivanovich <info@wwwlab.net> | -// +-----------------------------------------------------------------------+ -// - -//ob_start(); //-- For easy debugging --// - -require_once ("PEAR.php"); -require_once ("HTTP/Session.php"); - -ini_set('error_reporting', E_ALL); -ini_set('display_errors', 1); -//PEAR::setErrorHandling(PEAR_ERROR_DIE); - -//HTTP_Session::setContainer('DB', array('dsn' => 'mysql://root@localhost/database', 'table' => 'sessiondata')); -HTTP_Session::useCookies(true); -HTTP_Session::start('SessionID', uniqid('MyID')); - -?> -<html> -<head> -<style> -body, td { - font-family: Verdana, Arial, sans-serif; - font-size: 11px; -} -A:link { color:#003399; text-decoration: none; } -A:visited { color:#6699CC; text-decoration: none; } -A:hover { text-decoration: underline; } -</style> -<title>HTTP Session</title> -</head> -<body style="margin: 5px;"> -<?php - -/* -if (!isset($variable)) { - $variable = 0; - echo("The variable wasn't previously set<br>\n"); -} else { - $variable++; - echo("Yes, it was set already<br>\n"); -} -*/ - -switch (@$_GET['action']) { - case 'setvariable': - HTTP_Session::set('variable', 'Test string'); - //HTTP_Session::register('variable'); - break; - case 'unsetvariable': - HTTP_Session::set('variable', null); - //HTTP_Session::unregister('variable'); - break; - case 'clearsession': - HTTP_Session::clear(); - break; - case 'destroysession': - HTTP_Session::destroy(); - break; -} - -HTTP_Session::setExpire(60); -HTTP_Session::setIdle(5); - -//echo("session_is_registered('variable'): <b>'" . (session_is_registered('variable') ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); -//echo("isset(\$GLOBALS['variable']): <b>'" . (isset($GLOBALS['variable']) ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); - -echo("------------------------------------------------------------------<br>\n"); -echo("Session name: <b>'" . HTTP_Session::name() . "'</b><br>\n"); -echo("Session id: <b>'" . HTTP_Session::id() . "'</b><br>\n"); -echo("Is new session: <b>'" . (HTTP_Session::isNew() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); -echo("Is expired: <b>'" . (HTTP_Session::isExpired() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); -echo("Is idle: <b>'" . (HTTP_Session::isIdle() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); -//echo("Variable: <b>'" . HTTP_Session::get('variable') . "'</b><br>\n"); -echo("Session valid thru: <b>'" . (HTTP_Session::sessionValidThru() - time()) . "'</b><br>\n"); -echo("------------------------------------------------------------------<br>\n"); - -if (HTTP_Session::isNew()) { - //HTTP_Session::set('var', 'value'); - //HTTP_Session::setLocal('localvar', 'localvalue'); - //blah blah blah -} - -?> -<div style="background-color: #F0F0F0; padding: 15px; margin: 5px;"> -<pre> -$_SESSION: -<?php -var_dump($_SESSION); -?> -</pre> -</div> -<?php - -HTTP_Session::updateIdle(); - -?> -<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=setvariable">Set variable</a></p> -<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=unsetvariable">Unset variable</a></p> -<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=destroysession">Destroy session</a></p> -<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=clearsession">Clear session data</a></p> -<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>">Reload page</a></p> -</body> +<?php +// +// +-----------------------------------------------------------------------+ +// | Copyright (c) 2002, Alexander Radivanovich | +// | All rights reserved. | +// | | +// | Redistribution and use in source and binary forms, with or without | +// | modification, are permitted provided that the following conditions | +// | are met: | +// | | +// | o Redistributions of source code must retain the above copyright | +// | notice, this list of conditions and the following disclaimer. | +// | o Redistributions in binary form must reproduce the above copyright | +// | notice, this list of conditions and the following disclaimer in the | +// | documentation and/or other materials provided with the distribution.| +// | o The names of the authors may not be used to endorse or promote | +// | products derived from this software without specific prior written | +// | permission. | +// | | +// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | +// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | +// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | +// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | +// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | +// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT | +// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, | +// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY | +// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | +// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | +// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | +// | | +// +-----------------------------------------------------------------------+ +// | Author: Alexander Radivanovich <info@wwwlab.net> | +// +-----------------------------------------------------------------------+ +// + +//ob_start(); //-- For easy debugging --// + +require_once ("PEAR.php"); +require_once ("HTTP/Session.php"); + +ini_set('error_reporting', E_ALL); +ini_set('display_errors', 1); +//PEAR::setErrorHandling(PEAR_ERROR_DIE); + +//HTTP_Session::setContainer('DB', array('dsn' => 'mysql://root@localhost/database', 'table' => 'sessiondata')); +HTTP_Session::useCookies(true); +HTTP_Session::start('SessionID', uniqid('MyID')); + +?> +<html> +<head> +<style> +body, td { + font-family: Verdana, Arial, sans-serif; + font-size: 11px; +} +A:link { color:#003399; text-decoration: none; } +A:visited { color:#6699CC; text-decoration: none; } +A:hover { text-decoration: underline; } +</style> +<title>HTTP Session</title> +</head> +<body style="margin: 5px;"> +<?php + +/* +if (!isset($variable)) { + $variable = 0; + echo("The variable wasn't previously set<br>\n"); +} else { + $variable++; + echo("Yes, it was set already<br>\n"); +} +*/ + +switch (@$_GET['action']) { + case 'setvariable': + HTTP_Session::set('variable', 'Test string'); + //HTTP_Session::register('variable'); + break; + case 'unsetvariable': + HTTP_Session::set('variable', null); + //HTTP_Session::unregister('variable'); + break; + case 'clearsession': + HTTP_Session::clear(); + break; + case 'destroysession': + HTTP_Session::destroy(); + break; +} + +HTTP_Session::setExpire(60); +HTTP_Session::setIdle(5); + +//echo("session_is_registered('variable'): <b>'" . (session_is_registered('variable') ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); +//echo("isset(\$GLOBALS['variable']): <b>'" . (isset($GLOBALS['variable']) ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); + +echo("------------------------------------------------------------------<br>\n"); +echo("Session name: <b>'" . HTTP_Session::name() . "'</b><br>\n"); +echo("Session id: <b>'" . HTTP_Session::id() . "'</b><br>\n"); +echo("Is new session: <b>'" . (HTTP_Session::isNew() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); +echo("Is expired: <b>'" . (HTTP_Session::isExpired() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); +echo("Is idle: <b>'" . (HTTP_Session::isIdle() ? "<span style='color: red;'>yes</span>" : "no") . "'</b><br>\n"); +//echo("Variable: <b>'" . HTTP_Session::get('variable') . "'</b><br>\n"); +echo("Session valid thru: <b>'" . (HTTP_Session::sessionValidThru() - time()) . "'</b><br>\n"); +echo("------------------------------------------------------------------<br>\n"); + +if (HTTP_Session::isNew()) { + //HTTP_Session::set('var', 'value'); + //HTTP_Session::setLocal('localvar', 'localvalue'); + //blah blah blah +} + +?> +<div style="background-color: #F0F0F0; padding: 15px; margin: 5px;"> +<pre> +$_SESSION: +<?php +var_dump($_SESSION); +?> +</pre> +</div> +<?php + +HTTP_Session::updateIdle(); + +?> +<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=setvariable">Set variable</a></p> +<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=unsetvariable">Unset variable</a></p> +<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=destroysession">Destroy session</a></p> +<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>?action=clearsession">Clear session data</a></p> +<p><a href="<?php echo $_SERVER['SCRIPT_NAME'] ?>">Reload page</a></p> +</body> </html> \ No newline at end of file http://cvs.php.net/diff.php/pear/HTTP_Session/docs/sessiondata.sql?r1=1.1&r2=1.2&ty=u Index: pear/HTTP_Session/docs/sessiondata.sql diff -u pear/HTTP_Session/docs/sessiondata.sql:1.1 pear/HTTP_Session/docs/sessiondata.sql:1.2 --- pear/HTTP_Session/docs/sessiondata.sql:1.1 Sat Oct 4 19:29:17 2003 +++ pear/HTTP_Session/docs/sessiondata.sql Sat Apr 17 13:09:03 2004 @@ -1,7 +1,7 @@ -CREATE TABLE `sessiondata` ( - `id` varchar(32) NOT NULL default '', - `expiry` int(10) unsigned NOT NULL default '0', - `data` text NOT NULL, - PRIMARY KEY (`id`) -) TYPE=MyISAM; - +CREATE TABLE `sessiondata` ( + `id` varchar(32) NOT NULL default '', + `expiry` int(10) unsigned NOT NULL default '0', + `data` text NOT NULL, + PRIMARY KEY (`id`) +) TYPE=MyISAM; +
« previous php.pear.cvs (#18350) next »