Here is a php-based session library, including a namespace feature.
(BTW, is there a better place to contribute code to CI I don’t know about?)
It uses the PHP $_SESSION superglobal to read/write session data.
Further session management options (file/db container, etc) are then controlled
from the usual methods via php.ini.
like any CI library, you can either autoload it:
configs/autoload.php
$autoload['core'] = array('phpsession');
Or, load it manually inside any controller method:
$this->load->library('phpsession');
Example of usage from controller method:
function mymethod() {
$this->load->library('phpsession');
// save a variable to the session
$this->phpsession->save('foo','bar');
// save a variable in a namespace (other than default)
$this->phpsession->save('foo','bar','mynamespace');
// read a var from the session
$foo = $this->phpsession->get('foo');
// get var from a namespace
$foo = $this->phpsession->get('foo','mynamespace');
// get all session vars (from default namespace)
$all = $this->phpsession->get();
// get all session vars from given namespace
$all = $this->phpsession->get(null,'mynamespace');
// clear session var
$this->phpsession->clear('foo');
// clear all vars (default namespace)
$this->phpsession->clear();
// clear all vars in given namespace
$this->phpsession->clear(null, 'mynamespace');
// rest of your method
$this->load->view('myview');
}
To install phpsession, just drop these two files in the appropriate places:
application/init/init_phpsession.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
if ( ! class_exists('PhpSession'))
{
require_once(APPPATH.'libraries/phpsession'.EXT);
}
$obj =& get_instance();
$obj->phpsession = new PhpSession();
$obj->ci_is_loaded[] = 'phpsession';
?>
application/libraries/phpsession.php
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class PhpSession {
// constructor
function PhpSession() {
session_start();
}
function save($var, $val, $namespace = 'default') {
$_SESSION[$namespace][$var] = $val;
}
function get($var = null, $namespace = 'default') {
if(isset($var))
return isset($_SESSION[$namespace][$var]) ? $_SESSION[$namespace][$var] : null;
else
return isset($_SESSION[$namespace]) ? $_SESSION[$namespace] : null;
}
function clear($var = null, $namespace = 'default') {
if(isset($var))
unset($_SESSION[$namespace][$var]);
else
unset($_SESSION[$namespace]);
}
}
?>
