This is documentation for Kohana v2.3.x.
Status | Draft |
---|---|
Todo | Proof and perhaps a full example |
Enables applications to persist user state across pages
Sessions enable you to store and retrieve data between requests on a per-user basis. Typically, since each web page (or AJAX request, etc) is an individual request, there is no way to set a variable in one request and get its value in another. Sessions are one of several mechanisms that exist to overcome this limitation.
Sessions are useful where a small amount of data needs to persist across multiple page requests and where the data is specific to the particular browser session. For example, if your website has a “login” page, you may wish to remember, for one specific web browser only, that a particular user has logged-in.
If you want to store more general data between requests and it is less of an issue that the data be associated with only one browser session, other mechanisms may be more appropriate:
By default Kohana sessions are validated against the user-agent on each request. While providing some additional security, this will break any Flash-server integration which relies on access to the session, since Flash always provides its own user-agent string rather than that of the browser in which it is embedded. So if you are maintaining state during Flash-server communication, disable user-agent validation in config/session.php
.
To load the Session library, add the following code to your controller constructor, or to a particular controller method: Add the code:
$this->session = Session::instance();
The above line of code has two effects:
$this→session
.The following methods are available in the Session library:
$this→session→create()
can be called to create a new session. It will destroy any current session data.
Note that you do not need to call this method to enable sessions. Simply loading the Session library is enough to create a new session, or retrieve data from an existing session.
$this→session→id()
retrieves the ID of the current session.
For example,
echo 'Current session ID: ' . $this->session->id();
$this→session→regenerate()
causes the session ID to be regenerated whilst keeping all the current session data intact.
This can be done automatically by setting the session.regenerate config value to an integer greater than 0 (default value is 0). However, automatic session regeneration isn't recommended because it can cause a race condition when you have multiple session requests while regenerating the session id (most commonly noticed with ajax requests). For security reasons it's recommended that you manually call regenerate() whenever a visitor's session privileges are escalated (e.g. they logged in, accessed a restricted area, etc).
$this→session→destroy()
destroys all session data, including the browser cookie that is used to identify it.
The Session library arranges for PHPs inbuilt sessions array, $_SESSION
, to use the session libraries driver. This means that accessing session data can be done in the normal way. Note however this has been seen leading to unpredictable behavior if both $_SESSION and the session library methods are used.
For example,
// get some session data $data = $_SESSION['fish']; // set some session data $_SESSION['fish'] = 5;
In addition to this, the Session library also provides its own methods to deal with session data. These are:
$this→session→get($key = FALSE, $default = FALSE)
retrieves a named value from the session data.
$key
specifies the name of the data to retrieve from the session. If $key
is FALSE
, get()
returns an array containing all of the data in the current session.$default
specifies a default value to be returned if the named data does not exist in the session.For example,
// returns value of foo. If it doesn't exist, returns the string 'bar' instead. $value = $this->session->get('foo','bar');
$this→session→get_once($key)
works the same as get()
except that it also deletes the data from the current session afterwards.
For example,
// returns value of foo and deletes foo from the session. $value = $this->session->get_once('foo'); //it could also return default value 'bar' if it doesn't exists $value = $this->session->get_once('foo', 'bar');
$this→session→set($keys, $val = FALSE)
is used to set data in the current session.
$keys
can either specify the name of the data to set in the session, or it can be an array of “key ⇒ value” pairs (in which case the $val
argument is ignored).$keys
is the name of the data to set in the session, $val
specifies the value of that data.For example,
// set some_var to some_val $this->session->set('some_var', 'some_value'); // set several pieces of session data at once by passing an array to set() $this->session->set(array('fish' => 5, 'foo' => 'bar'));
$this→session→delete($keys)
is used to delete a piece of data from the current session.
$keys
specifies the name of the piece of data to delete from the session. It can also be a set of keys, each as a separate argument.For example,
// delete foo $this->session->delete('foo'); // delete several pieces of data from the session by passing each key as a separate argument $this->session->delete('bar', 'bas');
“Flash” session data is data that persists only until the next request. It could, for example, be used to show a message to a user only once.
As with other session data, you retrieve flash data using $this→session→get()
.
$this→session→set_flash($keys, $val = FALSE)
sets flash data in the current session.
$keys
can either specify the name of the data to set in the session, or it can be an array of “key ⇒ value” pairs (in which case the $val
argument is ignored).$keys
is the name of the data to set in the session, $val
specifies the value of that data.For example,
// set user_message flash session data $this->session->set_flash('user_message', 'Hello, how are you?'); // set several pieces of flash session data at once by passing an array $this->session->set_flash(array('user_message' => 'How are you?', 'fish' => 5));
Usually, flash data is automatically deleted after the next request. Sometimes this behaviour is not desired, though. For example, the next request might be an AJAX request for some data. In this case, you wouldn't want to delete your user_message
in the example above because it wouldn't have been shown to the user by the AJAX request.
$this→session→keep_flash($keys)
can be used to keep flash session data for one more request (aka “freshening” flash data).
$keys
specifies the name(s) of the flash session variables to keep.// Don't delete the user_message this request $this->session->keep_flash('user_message'); // Don't delete messages 1-3 $this->session->keep_flash('message1', 'message2', 'message3');
If you don't supply any arguments to the function all current flash session variables will be freshened.
// Don't delete any flash variable $this->session->keep_flash();
Edit the config file application/config/session.php
/* * File: Session * * Options: * driver - Session driver name: 'cookie','database', 'native' or 'cache' * storage - Session storage parameter, used by drivers (database and cache) * name - Default session name (alpha numeric chars only and the underscore) * validate - Session parameters to validate (user_agent, ip_address) * encryption - Encryption key, set to FALSE to disable session encryption * expiration - Number of seconds that each session will last (set to 0 for session which expires on browser exit) * regenerate - Number of page loads before the session is regenerated (set to 0 to disable automatic regeneration) * gc_probability - Percentage probability that garbage collection will be executed */ $config = array ( 'driver' => 'cookie', 'storage' => '', 'name' => 'kohanasession', 'validate' => array('user_agent'), 'encryption' => FALSE, 'expiration' => 7200, 'regenerate' => 3, 'gc_probability' => 2 );
By default session data is stored in a cookie. You can change this in the file config/session.php
.
The driver can be set here. Session name and other configuration options can also be set.
Available drivers and their storage containers :
Note: the cookie driver limits session data to 4KB, while the database driver limits session data to 64KB.
To use a database session, a Database and Table must exist.
By default, the session library will use the database you have configured in your default database group.
By default, the session library will look for a table called sessions
. (NB! The schema is changed from previous versions, see below)
You may configure your setup differently. Create a table to store the session.
CREATE TABLE sessions ( session_id VARCHAR(127) NOT NULL, last_activity INT(10) UNSIGNED NOT NULL, data TEXT NOT NULL, PRIMARY KEY (session_id) );
CREATE TABLE session ( session_id varchar(127) NOT NULL, last_activity integer NOT NULL, data text NOT NULL, CONSTRAINT session_id_pkey PRIMARY KEY (session_id), CONSTRAINT last_activity_check CHECK (last_activity >= 0) );
Configure session to use database:
$config['driver'] = 'database'; $config['storage'] = array( 'group' => 'db_group_name', // or use 'default' 'table' => 'session_table_name' // or use 'sessions' );
Available cache storage containers are:
Configure session to use a cache driver: The selected Cache storage container must be accessible and correctly configured.
$config['driver'] = 'cache'; $config['storage'] = array( 'driver' => 'apc', 'requests' => 10000 );
Lifetime does not need to be set as it is overridden by the session expiration setting.
Native PHP session mechanisms are used and you don't need anything else to make it work.
Note: if you are using Debian/Ubuntu and default storage directory /var/lib/php5, then set gc_probability to 0 and let the Debian/Ubuntu cron job clean the directory.
To retrieve the instantiated session library you can use the instance() method. If no instance is available, one will be created.
$session=Session::instance(); $var = $session->get('session_item');
Session instance methods can be called directly.
$var = Session::instance()->get('session_item'); Session::instance()->set('session_item', 'item value');
When using AJAX calls and sessions in Kohana, special care must be taken in regards to the “regenerate” option, which is set to 3 by default (as of Kohana 2.3).
What can happen is, since AJAX calls are asynchronous, Kohana will consider certain AJAX requests that come “out of order” to have expired sessions, since a new session ID is generated every 3 calls.
To avoid this, include the following line in your app's config/sessions.php:
$config['regenerate'] = 0;