HTTP_Session2
[ class tree: HTTP_Session2 ] [ index: HTTP_Session2 ] [ all elements ]

Source for file Session2.php

Documentation is available at Session2.php

  1. <?php
  2. //
  3. // +-----------------------------------------------------------------------+
  4. // | Copyright (c) 2004, Tony Bibbs                                        |
  5. // | All rights reserved.                                                  |
  6. // |                                                                       |
  7. // | Redistribution and use in source and binary forms, with or without    |
  8. // | modification, are permitted provided that the following conditions    |
  9. // | are met:                                                              |
  10. // |                                                                       |
  11. // | o Redistributions of source code must retain the above copyright      |
  12. // |   notice, this list of conditions and the following disclaimer.       |
  13. // | o Redistributions in binary form must reproduce the above copyright   |
  14. // |   notice, this list of conditions and the following disclaimer in the |
  15. // |   documentation and/or other materials provided with the distribution.|
  16. // | o The names of the authors may not be used to endorse or promote      |
  17. // |   products derived from this software without specific prior written  |
  18. // |   permission.                                                         |
  19. // |                                                                       |
  20. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
  21. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
  22. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  23. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
  24. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  25. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
  26. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  27. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  28. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
  29. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  30. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
  31. // |                                                                       |
  32. // +-----------------------------------------------------------------------+
  33. // | Author: Tony Bibbs <tony@geeklog.net>                                 |
  34. // +-----------------------------------------------------------------------+
  35. //
  36.  
  37.  
  38. /**
  39.  * PEAR::Exception
  40.  */
  41. require_once 'PEAR/Exception.php';
  42.  
  43. /** @const HTTP_SESSION2_STARTED - The session was started with the current request */
  44. define('HTTP_SESSION2_STARTED'1);
  45. /** @const HTTP_SESSION2_STARTED - No new session was started with the current request */
  46. define('HTTP_SESSION2_CONTINUED'2);
  47.  
  48. /**
  49.  * Class for managing HTTP sessions
  50.  *
  51.  * Provides access to session-state values as well as session-level
  52.  * settings and lifetime management methods.
  53.  * Based on the standart PHP session handling mechanism
  54.  * it provides for you more advanced features such as
  55.  * database container, idle and expire timeouts, etc.
  56.  *
  57.  * Expample 1:
  58.  *
  59.  * <code>
  60.  * // Setting some options and detecting of a new session
  61.  * HTTP_Session::setCookieless(false);
  62.  * HTTP_Session::start('MySessionID');
  63.  * HTTP_Session::set('variable', 'Tet string');
  64.  * if (HTTP_Session::isNew()) {
  65.  *     echo('new session was created with the current request');
  66.  *     $visitors++; // Increase visitors count
  67.  * }
  68.  * </code>
  69.  *
  70.  * Example 2:
  71.  *
  72.  * <code>
  73.  * // Using database container
  74.  * HTTP_Session::setContainer('DB');
  75.  * HTTP_Session::start();
  76.  * </code>
  77.  *
  78.  * Example 3:
  79.  *
  80.  * <code>
  81.  * // Setting timeouts
  82.  * HTTP_Session::start();
  83.  * HTTP_Session::setExpire(time() + 60 * 60); // expires in one hour
  84.  * HTTP_Session::setIdle(10 * 60);            // idles in ten minutes
  85.  * if (HTTP_Session::isExpired()) {
  86.  *     // expired
  87.  *     echo('Your session is expired!');
  88.  *     HTTP_Session::destroy();
  89.  * }
  90.  * if (HTTP_Session::isIdle()) {
  91.  *     // idle
  92.  *     echo('You've been idle for too long!');
  93.  *     HTTP_Session::destroy();
  94.  * }
  95.  * HTTP_Session::updateIdle();
  96.  * </code>
  97.  *
  98.  * @author  Alexander Radivaniovich <info@wwwlab.net>
  99.  * @author Tony Bibbs <tony@geeklog.net>
  100.  * @package HTTP_Session2
  101.  * @access  public
  102.  */
  103. class HTTP_Session2 {
  104.  
  105.     /**
  106.      * Sets user-defined session storage functions
  107.      *
  108.      * Sets the user-defined session storage functions which are used
  109.      * for storing and retrieving data associated with a session.
  110.      * This is most useful when a storage method other than
  111.      * those supplied by PHP sessions is preferred.
  112.      * i.e. Storing the session data in a local database.
  113.      *
  114.      * @static
  115.      * @access public
  116.      * @return void 
  117.      * @see    session_set_save_handler()
  118.      */
  119.     public function setContainer($container$container_options = null)
  120.     {
  121.         $container_class 'HTTP_Session2_Container_' $container;
  122.         $container_classfile 'HTTP/Session2/Container/' $container '.php';
  123.  
  124.         include_once $container_classfile;
  125.         if (!class_exists($container_class)) {
  126.             throw new PEAR_Exception("Container class, $container_class, does not exist");
  127.         }
  128.         $container = new $container_class($container_options);
  129.  
  130.         $container->set();
  131.     }
  132.  
  133.     /**
  134.      * Initializes session data
  135.      *
  136.      * Creates a session (or resumes the current one
  137.      * based on the session id being passed
  138.      * via a GET variable or a cookie).
  139.      * You can provide your own name and/or id for a session.
  140.      *
  141.      * @static
  142.      * @access public
  143.      * @param  $name  string Name of a session, default is 'SessionID'
  144.      * @param  $id    string Id of a session which will be used
  145.      *                        only when the session is new
  146.      * @return void 
  147.      * @see    session_name()
  148.      * @see    session_id()
  149.      * @see    session_start()
  150.      */
  151.     public function start($name 'SessionID'$id = null)
  152.     {
  153.         self::name($name);
  154.         if (is_null(self::detectID())) {
  155.             if ($id{
  156.                 self::id($id);
  157.             else {
  158.                 self::id(uniqid(dechex(rand())));
  159.             }
  160.         }
  161.         session_start();
  162.         if (!isset($_SESSION['__HTTP_Session2_Info'])) {
  163.             $_SESSION['__HTTP_Session2_Info'HTTP_SESSION2_STARTED;
  164.         else {
  165.             $_SESSION['__HTTP_Session2_Info'HTTP_SESSION2_CONTINUED;
  166.         }
  167.     }
  168.  
  169.     /**
  170.      * Writes session data and ends session
  171.      *
  172.      * Session data is usually stored after your script
  173.      * terminated without the need to call HTTP_Session::stop(),
  174.      * but as session data is locked to prevent concurrent
  175.      * writes only one script may operate on a session at any time.
  176.      * When using framesets together with sessions you will
  177.      * experience the frames loading one by one due to this
  178.      * locking. You can reduce the time needed to load all the
  179.      * frames by ending the session as soon as all changes
  180.      * to session variables are done.
  181.      *
  182.      * @static
  183.      * @access public
  184.      * @return void 
  185.      * @see    session_write_close()
  186.      */
  187.     public static function pause()
  188.     {
  189.         session_write_close();
  190.     }
  191.  
  192.     /**
  193.      * Frees all session variables and destroys all data
  194.      * registered to a session
  195.      *
  196.      * This method resets the $_SESSION variable and
  197.      * destroys all of the data associated
  198.      * with the current session in its storage (file or DB).
  199.      * It forces new session to be started after this method
  200.      * is called. It does not unset the session cookie.
  201.      *
  202.      * @static
  203.      * @access public
  204.      * @return void 
  205.      * @see    session_unset()
  206.      * @see    session_destroy()
  207.      */
  208.     public static function destroy()
  209.     {
  210.         session_unset();
  211.         session_destroy();
  212.     }
  213.  
  214.     /**
  215.      * Free all session variables
  216.      *
  217.      * @todo   TODO Save expire and idle timestamps?
  218.      * @static
  219.      * @access public
  220.      * @return void 
  221.      */
  222.     public static function clear()
  223.     {
  224.         $info $_SESSION['__HTTP_Session2_Info'];
  225.         session_unset();
  226.         $_SESSION['__HTTP_Session2_Info'$info;
  227.     }
  228.  
  229.     /**
  230.      * Tries to find any session id in $_GET, $_POST or $_COOKIE
  231.      *
  232.      * @static
  233.      * @access private
  234.      * @return string Session ID (if exists) or null
  235.      */
  236.     public static function detectID()
  237.     {
  238.         if (self::useCookies()) {
  239.             if (isset($_COOKIE[self::name()])) {
  240.                 return $_COOKIE[self::name()];
  241.             }
  242.         else {
  243.             if (isset($_GET[self::name()])) {
  244.                 return $_GET[self::name()];
  245.             }
  246.             if (isset($_POST[self::name()])) {
  247.                 return $_POST[self::name()];
  248.             }
  249.         }
  250.         return null;
  251.     }
  252.  
  253.     /**
  254.      * Sets new name of a session
  255.      *
  256.      * @static
  257.      * @access public
  258.      * @param  string $name New name of a sesion
  259.      * @return string Previous name of a session
  260.      * @see    session_name()
  261.      */
  262.     public static function name($name = null)
  263.     {
  264.         if (isset($name)) {
  265.             return session_name($name);
  266.         
  267.         
  268.         return session_name();
  269.     }
  270.  
  271.     /**
  272.      * Sets new ID of a session
  273.      *
  274.      * @static
  275.      * @access public
  276.      * @param  string $id New ID of a sesion
  277.      * @return string Previous ID of a session
  278.      * @see    session_id()
  279.      */
  280.     public static function id($id = null)
  281.     {
  282.         if (isset($id)) {
  283.             return session_id($id);
  284.         }
  285.         
  286.         return session_id();
  287.     }
  288.  
  289.     /**
  290.      * Sets the maximum expire time
  291.      *
  292.      * @static
  293.      * @access public
  294.      * @param  integer $time Time in seconds
  295.      * @param  bool    $add  Add time to current expire time or not
  296.      * @return void 
  297.      */
  298.     public static function setExpire($time$add = false)
  299.     {
  300.         if ($add{
  301.             $GLOBALS['__HTTP_Session2_Expire'+= $time;
  302.         else {
  303.             $GLOBALS['__HTTP_Session2_Expire'$time;
  304.         }
  305.         if (!isset($_SESSION['__HTTP_Session2_Expire_TS'])) {
  306.             $_SESSION['__HTTP_Session2_Expire_TS'time();
  307.         }
  308.     }
  309.  
  310.     /**
  311.      * Sets the maximum idle time
  312.      *
  313.      * Sets the time-out period allowed
  314.      * between requests before the session-state
  315.      * provider terminates the session.
  316.      *
  317.      * @static
  318.      * @access public
  319.      * @param  integer $time Time in seconds
  320.      * @param  bool    $add  Add time to current maximum idle time or not
  321.      * @return void 
  322.      */
  323.     public static function setIdle($time$add = false)
  324.     {
  325.         if ($add{
  326.             $GLOBALS['__HTTP_Session2_Idle'+= $time;
  327.         else {
  328.             $GLOBALS['__HTTP_Session2_Idle'$time;
  329.         }
  330.         if (!isset($_SESSION['__HTTP_Session2_Idle_TS'])) {
  331.             $_SESSION['__HTTP_Session2_Idle_TS'time();
  332.         }
  333.     }
  334.  
  335.     /**
  336.      * Returns the time up to the session is valid
  337.      *
  338.      * @static
  339.      * @access public
  340.      * @return integer Time when the session idles
  341.      */
  342.     public static function sessionValidThru()
  343.     {
  344.         if (!isset($_SESSION['__HTTP_Session2_Idle_TS']|| !isset($GLOBALS['__HTTP_Session2_Idle'])) {
  345.             return 0;
  346.         else {
  347.             return $_SESSION['__HTTP_Session2_Idle_TS'$GLOBALS['__HTTP_Session2_Idle'];
  348.         }
  349.     }
  350.  
  351.     /**
  352.      * Check if session is expired
  353.      *
  354.      * @static
  355.      * @access public
  356.      * @return boolean Obvious
  357.      */
  358.     public static function isExpired()
  359.     {
  360.         if ($GLOBALS['__HTTP_Session2_Expire'> 0 && isset($_SESSION['__HTTP_Session2_Expire_TS']&&
  361.             ($_SESSION['__HTTP_Session2_Expire_TS'$GLOBALS['__HTTP_Session2_Expire']<= time()) {
  362.             return true;
  363.         else {
  364.             return false;
  365.         }
  366.     }
  367.  
  368.     /**
  369.      * Check if session is idle
  370.      *
  371.      * @static
  372.      * @access public
  373.      * @return boolean Obvious
  374.      */
  375.     public static function isIdle()
  376.     {
  377.         if ($GLOBALS['__HTTP_Session2_Idle'> 0 && isset($_SESSION['__HTTP_Session2_Idle_TS']&&
  378.             ($_SESSION['__HTTP_Session2_Idle_TS'$GLOBALS['__HTTP_Session2_Idle']<= time()) {
  379.             return true;
  380.         else {
  381.             return false;
  382.         }
  383.     }
  384.  
  385.     /**
  386.      * Updates the idletime
  387.      *
  388.      * @static
  389.      * @access public
  390.      * @return void 
  391.      */
  392.     public static function updateIdle()
  393.     {
  394.         if (isset($_SESSION['__HTTP_Session2_Idle_TS'])) {
  395.             $_SESSION['__HTTP_Session2_Idle_TS'time();
  396.         }
  397.     }
  398.  
  399.     /**
  400.      * If optional parameter is specified it indicates
  401.      * whether the module will use cookies to store
  402.      * the session id on the client side
  403.      *
  404.      * It returns the previous value of this property
  405.      *
  406.      * @static
  407.      * @access public
  408.      * @param  boolean $useCookies If specified it will replace the previous value
  409.      *                              of this property
  410.      * @return boolean The previous value of the property
  411.      */
  412.     public static function useCookies($useCookies = null)
  413.     {
  414.         if (ini_get('session.use_cookies')) {
  415.             $return = true;
  416.         else {
  417.             $return = false;
  418.         }
  419.         if (isset($useCookies)) {
  420.             if ($useCookies{
  421.                 ini_set('session.use_cookies',1);
  422.             else {
  423.                 ini_set('session.use_cookies',0);
  424.             }
  425.         }
  426.         return $return;
  427.     }
  428.  
  429.     /**
  430.      * Gets a value indicating whether the session
  431.      * was created with the current request
  432.      *
  433.      * You MUST call this method only after you have started
  434.      * the session with the HTTP_Session::start() method.
  435.      *
  436.      * @static
  437.      * @access public
  438.      * @return boolean true if the session was created
  439.      *                  with the current request, false otherwise
  440.      */
  441.     public static function isNew()
  442.     {
  443.         // The best way to check if a session is new is to check
  444.         // for existence of a session data storage
  445.         // with the current session id, but this is impossible
  446.         // with the default PHP module wich is 'files'.
  447.         // So we need to emulate it.
  448.         return !isset($_SESSION['__HTTP_Session2_Info']||
  449.             $_SESSION['__HTTP_Session2_Info'== HTTP_SESSION2_STARTED;
  450.     }
  451.  
  452.     /**
  453.      * Register variable with the current session
  454.      *
  455.      * @static
  456.      * @access public
  457.      * @param  string $name Name of a global variable
  458.      * @return void 
  459.      * @see    session_register()
  460.      */
  461.     public static function register($name)
  462.     {
  463.         session_register($name);
  464.     }
  465.  
  466.     /**
  467.      * Unregister a variable from the current session
  468.      *
  469.      * @static
  470.      * @access public
  471.      * @param  string $name Name of a global variable
  472.      * @return void 
  473.      * @see    session_unregister()
  474.      */
  475.     public static function unregister($name)
  476.     {
  477.         session_unregister($name);
  478.     }
  479.  
  480.     /**
  481.      * Returns session variable
  482.      *
  483.      * @static
  484.      * @access public
  485.      * @param  string $name    Name of a variable
  486.      * @param  mixed  $default Default value of a variable if not set
  487.      * @return mixed  Value of a variable
  488.      */
  489.     public static function &get($name$default = null)
  490.     {
  491.         if (!isset($_SESSION[$name]&& isset($default)) {
  492.             $_SESSION[$name$default;
  493.         }
  494.         return $_SESSION[$name];
  495.     }
  496.  
  497.     /**
  498.      * Sets session variable
  499.      *
  500.      * @access public
  501.      * @param  string $name  Name of a variable
  502.      * @param  mixed  $value Value of a variable
  503.      * @return mixed  Old value of a variable
  504.      */
  505.     public function set($name$value)
  506.     {
  507.         $return @$_SESSION[$name];
  508.         if (null === $value{
  509.             unset($_SESSION[$name]);
  510.         else {
  511.             $_SESSION[$name$value;
  512.         }
  513.         return $return;
  514.     }
  515.  
  516.     /**
  517.      * Returns local variable of a script
  518.      *
  519.      * Two scripts can have local variables with the same names
  520.      *
  521.      * @static
  522.      * @access public
  523.      * @param  string $name    Name of a variable
  524.      * @param  mixed  $default Default value of a variable if not set
  525.      * @return mixed  Value of a local variable
  526.      */
  527.     public static function &getLocal($name$default = null)
  528.     {
  529.         $local md5(self::localName());
  530.         if (!is_array($_SESSION[$local])) {
  531.             $_SESSION[$local= array();
  532.         }
  533.         if (!isset($_SESSION[$local][$name]&& isset($default)) {
  534.             $_SESSION[$local][$name$default;
  535.         }
  536.         return $_SESSION[$local][$name];
  537.     }
  538.  
  539.     /**
  540.      * Sets local variable of a script.
  541.      * Two scripts can have local variables with the same names.
  542.      *
  543.      * @static
  544.      * @access public
  545.      * @param  string $name  Name of a local variable
  546.      * @param  mixed  $value Value of a local variable
  547.      * @return mixed  Old value of a local variable
  548.      */
  549.     public static function setLocal($name$value)
  550.     {
  551.         $local md5(self::localName());
  552.         if (!is_array($_SESSION[$local])) {
  553.             $_SESSION[$local= array();
  554.         }
  555.         $return $_SESSION[$local][$name];
  556.         if (null === $value{
  557.             unset($_SESSION[$local][$name]);
  558.         else {
  559.             $_SESSION[$local][$name$value;
  560.         }
  561.         return $return;
  562.     }
  563.  
  564.     /**
  565.      * Sets new local name
  566.      *
  567.      * @static
  568.      * @access public
  569.      * @param  string New local name
  570.      * @return string Previous local name
  571.      */
  572.     public static function localName($name = null)
  573.     {
  574.         $return @$GLOBALS['__HTTP_Session2_Localname'];
  575.         if (!empty($name)) {
  576.             $GLOBALS['__HTTP_Session2_Localname'$name;
  577.         }
  578.         return $return;
  579.     }
  580.  
  581.     /**
  582.      *
  583.      * @static
  584.      * @access private
  585.      * @return void 
  586.      */
  587.     public static function init()
  588.     {
  589.         // Disable auto-start of a sesion
  590.         ini_set('session.auto_start'0);
  591.  
  592.         // Set local name equal to the current script name
  593.         self::localName($_SERVER['SCRIPT_NAME']);
  594.     }
  595. }
  596.  
  597.  
  598. ?>

Documentation generated on Mon, 11 Mar 2019 14:18:39 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.