Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 35 revisions

Category:Libraries::Session

Native_session library was written for those who prefer to use native PHP session handling features over the original CI session implementation and require additional security.

[h3] Benefits over CI_Session [/h3]

  • hardened against session fixation by cookie id TTL (time to live) - regenerates cookie id automatically every given amount of time (right now configured inside the class) - see Note about making it setable.
  • you can use all available PHP session storage drivers (database, memcache, etc.)
  • "flash" session attributes (see: "Flash" attributes)

[h3] Benefits over PHPsession [/h3]

  • compatible with CI_Session
    • the same way of use, just load the library, set_userdata(), userdata()
    • easy to migrate existing apps to Native_session
    • need docs - use the CI manual :)
  • better security (automatic and manual session id regeneration)

PHPsession introduces concept of session namespace, which IMHO encourages you to use large number of the the session vars. I prefer to limit the use of sessions as much as possible (because of the potential scalability problems), so the Native_session won't implement session namespaces.

[h3] Usage [/h3]

  • the same as the original CI session library - just load the library and access the session data via session->userdata() and session->set_userdata() methods
  • allows to regenerate cookie id manually by calling session->regenerate_id()

[h3] Flash attributes [/h3]

You can set the session attribute that will persist only for the next request. The usage is similar to the session->set_userdata($key, $value), userdata($key):

  • set_flashdata($key, $value) - sets the flash attribute
  • flashdata($key) - gets the value of the given flash attribute
  • keep_flashdata($key) - make the given flash attribute valid for one more request

The implementation of flash attributes is based on the Native_session session implementation, which means it uses the PHP native session handling features.

The original concept:

  • PHPsession
  • [url=http://www.codeigniter.com/forums/viewthread/529/]Discussion thread[/url]

[h3]Variable Session Times[/h3]

  • Locate the _sess_run() function. Add this at the start of the function: [code] $session_id_ttl = $this->object->config->item('sess_expiration');

      if (is_numeric($session_id_ttl))
      {
          if ($session_id_ttl > 0)
          {
              $this->session_id_ttl = $this->object->config->item('sess_expiration');
          }
          else
          {
              $this->session_id_ttl = (60*60*24*365*2);
          }
      }
    

[/code]

  • Remove the number set at the top of the class implementation: [code]var $session_id_ttl;[/code]

  • Add [code]$this->object =& get_instance();[/code] to the top of the Native_session() function

  • It should now pick up the [code]$config['sess_expiration'] = 7200;[/code] line in your config.php file.

  • Added by HushPe

[h3] Files [/h3]

Contents of system/application/libraries/native_session.php:

[code] <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); /**

// ------------------------------------------------------------------------

/**

  • Session class using native PHP session features and hardened against session fixation.

  • @package CodeIgniter

  • @subpackage Libraries

  • @category Sessions

  • @author Dariusz Debowczyk

  • @link http://www.codeigniter.com/user_guide/libraries/sessions.html */ class Native_session { var $session_id_ttl = 360; // session id time to live (TTL) in seconds var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)

    function Native_session() { log_message('debug', "Native_session Class Initialized"); $this->_sess_run(); }

    /**

    • Regenerates session id */ function regenerate_id() { // copy old session data, including its id $old_session_id = session_id(); $old_session_data = $_SESSION;

      // regenerate session id and store it session_regenerate_id(); $new_session_id = session_id();

      // switch to the old session and destroy its storage session_id($old_session_id); session_destroy();

      // switch back to the new session id and send the cookie session_id($new_session_id); session_start();

      // restore the old session data into the new session $_SESSION = $old_session_data;

      // update the session creation time $_SESSION['regenerated'] = time();

      // session_write_close() patch based on this thread // http://www.codeigniter.com/forums/viewthread/1624/ // there is a question mark ?? as to side affects

      // end the current session and store session data. session_write_close(); }

    /**

    • Destroys the session and erases session storage */ function destroy() { unset($_SESSION); if ( isset( $_COOKIE[session_name()] ) ) { setcookie(session_name(), '', time()-42000, '/'); } session_destroy(); }

    /**

    • Reads given session attribute value */
      function userdata($item) { if($item == 'session_id'){ //added for backward-compatibility return session_id(); }else{ return ( ! isset($_SESSION[$item])) ? false : $_SESSION[$item]; } }

    /**

    • Sets session attributes to the given values */ function set_userdata($newdata = array(), $newval = '') { if (is_string($newdata)) { $newdata = array($newdata => $newval); }

      if (count($newdata) > 0) { foreach ($newdata as $key => $val) { $_SESSION[$key] = $val; } } }

    /**

    • Erases given session attributes */ function unset_userdata($newdata = array()) { if (is_string($newdata)) { $newdata = array($newdata => ''); }

      if (count($newdata) > 0) { foreach ($newdata as $key => $val) { unset($_SESSION[$key]); } }
      }

    /**

    • Starts up the session system for current request */ function _sess_run() { session_start();

      // check if session id needs regeneration if ( $this->_session_id_expired() ) { // regenerate session id (session data stays the // same, but old session storage is destroyed) $this->regenerate_id(); }

      // delete old flashdata (from last request) $this->_flashdata_sweep();

      // mark all new flashdata as old (data will be deleted before next request) $this->_flashdata_mark(); }

    /**

    • Checks if session has expired */ function _session_id_expired() { if ( !isset( $_SESSION['regenerated'] ) ) { $_SESSION['regenerated'] = time(); return false; }

      $expiry_time = time() - $this->session_id_ttl;

      if ( $_SESSION['regenerated'] <= $expiry_time ) { return true; }

      return false; }

    /**

    • Sets "flash" data which will be available only in next request (then it will
    • be deleted from session). You can use it to implement "Save succeeded" messages
    • after redirect. */ function set_flashdata($key, $value) { $flash_key = $this->flash_key.':new:'.$key; $this->set_userdata($flash_key, $value); }

    /**

    • Keeps existing "flash" data available to next request. */ function keep_flashdata($key) { $old_flash_key = $this->flash_key.':old:'.$key; $value = $this->userdata($old_flash_key);

      $new_flash_key = $this->flash_key.':new:'.$key; $this->set_userdata($new_flash_key, $value); }

    /**

    • Returns "flash" data for the given key. */ function flashdata($key) { $flash_key = $this->flash_key.':old:'.$key; return $this->userdata($flash_key); }

    /**

    • PRIVATE: Internal method - marks "flash" session attributes as 'old' */ function _flashdata_mark() { foreach ($_SESSION as $name => $value) { $parts = explode(':new:', $name); if (is_array($parts) && count($parts) == 2) { $new_name = $this->flash_key.':old:'.$parts[1]; $this->set_userdata($new_name, $value); $this->unset_userdata($name); } } }

    /**

    • PRIVATE: Internal method - removes "flash" session marked as 'old' */ function _flashdata_sweep() { foreach ($_SESSION as $name => $value) { $parts = explode(':old:', $name); if (is_array($parts) && count($parts) == 2 && $parts[0] == $this->flash_key) { $this->unset_userdata($name); } } } } ?> [/code]

Contents of system/application/init/init_native_session.php:

[code] <?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**

  • Loads and instantiates native session class */

if ( ! class_exists('Native_session')) { require_once(APPPATH.'libraries/Native_session'.EXT); }

// sessions engine should run on cookies to minimize opportunities // of session fixation attack ini_set('session.use_only_cookies', 1);

$obj =& get_instance(); $obj->session = new Native_session(); $obj->ci_is_loaded[] = 'session';

?> [/code]

[h3]Modifications for Vesion 1.5 [/h3] CodeIgniter changes the way libraries are created and used in Version 1.5. To upgrade your Native_session library, do the following:

  • Remove the init/init_native_session.php file. This file is no longer used by CodeIgniter.
  • Rename the libraries/native_session.php file to libraries/Session.php
  • Rename the Class in libraries/Session.php and Class Constructor to Session as follow: [ocde] // class Native_session() { // USE THE LINE BELOW INSTEAD class CI_Session() { var $session_id_ttl = 360; // session id time to live (TTL) in seconds var $flash_key = 'flash'; // prefix for "flash" variables (eg. flash:new:message)

// function Native_session() // USE THE LINE BELOW INSTEAD function CI_Session() { log_message('debug', "Native_session Class Initialized"); $this->_sess_run(); } $this->_sess_run(); [/code]

  • In your application code, change your native session loading code as follows: [code] // $this->load->library('Native_session'); // USE THE LINE BELOW INSTEAD $this->load->library('session'); [/code]
Clone this wiki locally