1 # Using Sessions and Cookies
3 Kohana provides a couple of classes that make it easy to work with both cookies and session. At a high level both sessions and cookies provide the same function. They allow the developer to store temporary or persistent information about a specific client for later retrieval.
5 Cookies should be used for storing non-private data that is persistent for a long period of time. For example storing a user id or a language preference. Use the [Cookie] class for getting and setting cookies.
7 [!!] Kohana uses "signed" cookies. Every cookie that is stored is combined with a secure hash to prevent modification of the cookie. This hash is generated using [Cookie::salt], which uses the [Cookie::$salt] property. You should [change this setting](using.configuration) when your application is live.
9 Sessions should be used for storing temporary or private data. Very sensitive data should be stored using the [Session] class with the "database" or "native" adapters. When using the "cookie" adapter, the session should always be encrypted.
11 [!!] For more information on best practices with session variables see [the seven deadly sins of sessions](http://lists.nyphp.org/pipermail/talk/2006-December/020358.html).
13 # Storing, Retrieving, and Deleting Data
15 [Cookie] and [Session] provide a very similar API for storing data. The main difference between them is that sessions are accessed using an object, and cookies are accessed using a static class.
17 Accessing the session instance is done using the [Session::instance] method:
19 // Get the session instance
20 $session = Session::instance();
22 When using sessions, you can also get all of the current session data using the [Session::as_array] method:
24 // Get all of the session data as an array
25 $data = $session->as_array();
27 You can also use this to overload the `$_SESSION` global to get and set data in a way more similar to standard PHP:
29 // Overload $_SESSION with the session data
30 $_SESSION =& $session->as_array();
33 $_SESSION[$key] = $value;
35 ## Storing Data {#setting}
37 Storing session or cookie data is done using the `set` method:
40 $session->set($key, $value);
43 Cookie::set($key, $value);
46 $session->set('user_id', 10);
47 Cookie::set('user_id', 10);
49 ## Retrieving Data {#getting}
51 Getting session or cookie data is done using the `get` method:
54 $data = $session->get($key, $default_value);
57 $data = Cookie::get($key, $default_value);
60 $user = $session->get('user_id');
61 $user = Cookie::get('user_id');
63 ## Deleting Data {#deleting}
65 Deleting session or cookie data is done using the `delete` method:
67 // Delete session data
68 $session->delete($key);
74 $session->delete('user_id');
75 Cookie::delete('user_id');
77 # Configuration {#configuration}
79 Both cookies and sessions have several configuration settings which affect how data is stored. Always check these settings before making your application live, as many of them will have a direct affect on the security of your application.
83 All of the cookie settings are changed using static properties. You can either change these settings in `bootstrap.php` or by using a [class extension](using.autoloading#class-extension).
85 The most important setting is [Cookie::$salt], which is used for secure signing. This value should be changed and kept secret:
87 Cookie::$salt = 'your secret is safe with me';
89 [!!] Changing this value will render all cookies that have been set before invalid.
91 By default, cookies are stored until the browser is closed. To use a specific lifetime, change the [Cookie::$expiration] setting:
93 // Set cookies to expire after 1 week
94 Cookie::$expiration = 604800;
96 // Alternative to using raw integers, for better clarity
97 Cookie::$expiration = Date::WEEK;
99 The path that the cookie can be accessed from can be restricted using the [Cookie::$path] setting.
101 // Allow cookies only when going to /public/*
102 Cookie::$path = '/public/';
104 The domain that the cookie can be accessed from can also be restricted, using the [Cookie::$domain] setting.
106 // Allow cookies only on the domain www.example.com
107 Cookie::$domain = 'www.example.com';
109 If you want to make the cookie accessible on all subdomains, use a dot at the beginning of the domain.
111 // Allow cookies to be accessed on example.com and *.example.com
112 Cookie::$domain = '.example.com';
114 To only allow the cookie to be accessed over a secure (HTTPS) connection, use the [Cookie::$secure] setting.
116 // Allow cookies to be accessed only on a secure connection
117 Cookie::$secure = TRUE;
119 // Allow cookies to be accessed on any connection
120 Cookie::$secure = FALSE;
122 To prevent cookies from being accessed using Javascript, you can change the [Cookie::$httponly] setting.
124 // Make cookies inaccessible to Javascript
125 Cookie::$httponly = TRUE;
127 ## Session Adapters {#adapters}
129 When creating or accessing an instance of the [Session] class you can decide which session adapter you wish to use. The session adapters that are available to you are:
132 : Stores session data in the default location for your web server. The storage location is defined by [session.save_path](http://php.net/manual/session.configuration.php#ini.session.save-path) in `php.ini` or defined by [ini_set](http://php.net/ini_set).
135 : Stores session data in a database table using the [Session_Database] class. Requires the [Database] module to be enabled.
138 : Stores session data in a cookie using the [Cookie] class. **Sessions will have a 4KB limit when using this adapter.**
140 The default datapter can be set by changing the value of [Session::$default]. The default adapter is "native".
142 [!!] As with cookies, a "lifetime" setting of "0" means that the session will expire when the browser is closed.
144 ### Session Adapter Settings
146 You can apply configuration settings to each of the session adapters by creating a session config file at `APPPATH/config/session.php`. The following sample configuration file defines all the settings for each adapater:
150 'name' => 'session_name',
154 'name' => 'cookie_name',
159 'name' => 'cookie_name',
162 'group' => 'default',
163 'table' => 'table_name',
165 'session_id' => 'session_id',
166 'last_active' => 'last_active',
167 'contents' => 'contents'
173 #### Native Adapter {#adapter-native}
175 Type | Setting | Description | Default
176 ----------|-----------|---------------------------------------------------|-----------
177 `string` | name | name of the session | `"session"`
178 `integer` | lifetime | number of seconds the session should live for | `0`
180 #### Cookie Adapter {#adapter-cookie}
182 Type | Setting | Description | Default
183 ----------|-----------|---------------------------------------------------|-----------
184 `string` | name | name of the cookie used to store the session data | `"session"`
185 `boolean` | encrypted | encrypt the session data using [Encrypt]? | `FALSE`
186 `integer` | lifetime | number of seconds the session should live for | `0`
188 #### Database Adapter {#adapter-database}
190 Type | Setting | Description | Default
191 ----------|-----------|---------------------------------------------------|-----------
192 `string` | group | [Database::instance] group name | `"default"`
193 `string` | table | table name to store sessions in | `"sessions"`
194 `array` | columns | associative array of column aliases | `array`
195 `integer` | gc | 1:x chance that garbage collection will be run | `500`
196 `string` | name | name of the cookie used to store the session data | `"session"`
197 `boolean` | encrypted | encrypt the session data using [Encrypt]? | `FALSE`
198 `integer` | lifetime | number of seconds the session should live for | `0`
202 You will need to create the session storage table in the database. This is the default schema:
204 CREATE TABLE `sessions` (
205 `session_id` VARCHAR(24) NOT NULL,
206 `last_active` INT UNSIGNED NOT NULL,
207 `contents` TEXT NOT NULL,
208 PRIMARY KEY (`session_id`),
209 INDEX (`last_active`)
214 You can change the column names to match an existing database schema when connecting to a legacy session table. The default value is the same as the key value.
217 : the name of the "id" column
220 : UNIX timestamp of the last time the session was updated
223 : session data stored as a serialized string, and optionally encrypted