blob: aecad3164fcbaed93f17566af4297c83b33f6755 [file] [log] [blame]
dchill423169f262012-08-11 20:12:05 -04001##############
2Session Driver
3##############
Derek Jones8ede1a22011-10-05 13:34:52 -05004
5The Session class permits you maintain a user's "state" and track their
dchill423169f262012-08-11 20:12:05 -04006activity while they browse your site. CodeIgniter offers two default
7session drivers: the classic `Cookie Driver`_, and the `Native Driver`_,
8which supports usage of the native PHP Session mechanism. In addition,
9you may create your own `Custom Drivers`_ to store session data however
10you wish, while still taking advantage of the features of the Session class.
Derek Jones8ede1a22011-10-05 13:34:52 -050011
12Initializing a Session
13======================
14
15Sessions will typically run globally with each page load, so the session
dchill423169f262012-08-11 20:12:05 -040016class must either be :doc:`initialized <../general/drivers>` in your
Derek Jones8ede1a22011-10-05 13:34:52 -050017:doc:`controller <../general/controllers>` constructors, or it can be
18:doc:`auto-loaded <../general/autoloader>` by the system. For the most
19part the session class will run unattended in the background, so simply
20initializing the class will cause it to read, create, and update
21sessions.
22
23To initialize the Session class manually in your controller constructor,
dchill423169f262012-08-11 20:12:05 -040024use the $this->load->driver function::
Derek Jones8ede1a22011-10-05 13:34:52 -050025
dchill423169f262012-08-11 20:12:05 -040026 $this->load->driver('session');
Derek Jones8ede1a22011-10-05 13:34:52 -050027
28Once loaded, the Sessions library object will be available using:
29$this->session
30
dchill423169f262012-08-11 20:12:05 -040031.. note:: For backward compatibility, the Session class may stil be loaded
32 using the $this->load->library function, but converting your applications
33 to use $this->load->driver is strongly recommended.
34
Derek Jones8ede1a22011-10-05 13:34:52 -050035How do Sessions work?
36=====================
37
38When a page is loaded, the session class will check to see if valid
dchill423169f262012-08-11 20:12:05 -040039session data exists in the user's session. If sessions data does **not**
40exist (or if it has expired) a new session will be created and saved.
41If a session does exist, its information will be updated. With each update,
42the session_id will be regenerated.
Derek Jones8ede1a22011-10-05 13:34:52 -050043
44It's important for you to understand that once initialized, the Session
45class runs automatically. There is nothing you need to do to cause the
46above behavior to happen. You can, as you'll see below, work with
47session data or even add your own data to a user's session, but the
48process of reading, writing, and updating a session is automatic.
49
50What is Session Data?
51=====================
52
53A *session*, as far as CodeIgniter is concerned, is simply an array
54containing the following information:
55
56- The user's unique Session ID (this is a statistically random string
57 with very strong entropy, hashed with MD5 for portability, and
58 regenerated (by default) every five minutes)
59- The user's IP Address
60- The user's User Agent data (the first 120 characters of the browser
61 data string)
62- The "last activity" time stamp.
63
64The above data is stored in a cookie as a serialized array with this
65prototype::
66
Derek Jones4b83d912011-10-05 15:42:30 -050067 [array]
68 (
69 'session_id' => random hash,
70 'ip_address' => 'string - user IP address',
71 'user_agent' => 'string - user agent data',
72 'last_activity' => timestamp
73 )
Derek Jones8ede1a22011-10-05 13:34:52 -050074
dchill423169f262012-08-11 20:12:05 -040075.. note:: Sessions are only updated every five minutes by default to
76 reduce processor load. If you repeatedly reload a page you'll notice
77 that the "last activity" time only updates if five minutes or more has
78 passed since the last time the cookie was written. This time is
79 configurable by changing the $config['sess_time_to_update'] line in
80 your system/config/config.php file.
Derek Jones8ede1a22011-10-05 13:34:52 -050081
82Retrieving Session Data
83=======================
84
85Any piece of information from the session array is available using the
86following function::
87
88 $this->session->userdata('item');
89
90Where item is the array index corresponding to the item you wish to
91fetch. For example, to fetch the session ID you will do this::
92
93 $session_id = $this->session->userdata('session_id');
94
dchill423169f262012-08-11 20:12:05 -040095.. note:: The function returns NULL if the item you are
Derek Jones8ede1a22011-10-05 13:34:52 -050096 trying to access does not exist.
97
98Adding Custom Session Data
99==========================
100
101A useful aspect of the session array is that you can add your own data
102to it and it will be stored in the user's cookie. Why would you want to
103do this? Here's one example:
104
105Let's say a particular user logs into your site. Once authenticated, you
dchill423169f262012-08-11 20:12:05 -0400106could add their username and email address to the session, making
Derek Jones8ede1a22011-10-05 13:34:52 -0500107that data globally available to you without having to run a database
108query when you need it.
109
110To add your data to the session array involves passing an array
111containing your new data to this function::
112
113 $this->session->set_userdata($array);
114
115Where $array is an associative array containing your new data. Here's an
116example::
117
Derek Jones4b83d912011-10-05 15:42:30 -0500118 $newdata = array(
119 'username' => 'johndoe',
120 'email' => 'johndoe@some-site.com',
121 'logged_in' => TRUE
122 );
Derek Jones8ede1a22011-10-05 13:34:52 -0500123
Derek Jones4b83d912011-10-05 15:42:30 -0500124 $this->session->set_userdata($newdata);
Derek Jones8ede1a22011-10-05 13:34:52 -0500125
126If you want to add userdata one value at a time, set_userdata() also
127supports this syntax.
128
129::
130
131 $this->session->set_userdata('some_name', 'some_value');
132
dchill423169f262012-08-11 20:12:05 -0400133If you want to verify that a userdata value exists, call has_userdata().
Derek Jones8ede1a22011-10-05 13:34:52 -0500134
dchill423169f262012-08-11 20:12:05 -0400135::
136
137 $this->session->has_userdata('some_name');
Derek Jones8ede1a22011-10-05 13:34:52 -0500138
139Retrieving All Session Data
140===========================
141
142An array of all userdata can be retrieved as follows::
143
144 $this->session->all_userdata()
145
146And returns an associative array like the following::
147
Derek Jones4b83d912011-10-05 15:42:30 -0500148 Array
149 (
150 [session_id] => 4a5a5dca22728fb0a84364eeb405b601
151 [ip_address] => 127.0.0.1
152 [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
153 [last_activity] => 1303142623
154 )
Derek Jones8ede1a22011-10-05 13:34:52 -0500155
156Removing Session Data
157=====================
158
159Just as set_userdata() can be used to add information into a session,
160unset_userdata() can be used to remove it, by passing the session key.
161For example, if you wanted to remove 'some_name' from your session
162information::
163
164 $this->session->unset_userdata('some_name');
165
166
167This function can also be passed an associative array of items to unset.
168
169::
170
Derek Jones4b83d912011-10-05 15:42:30 -0500171 $array_items = array('username' => '', 'email' => '');
172
173 $this->session->unset_userdata($array_items);
Derek Jones8ede1a22011-10-05 13:34:52 -0500174
175
176Flashdata
177=========
178
179CodeIgniter supports "flashdata", or session data that will only be
180available for the next server request, and are then automatically
181cleared. These can be very useful, and are typically used for
182informational or status messages (for example: "record 2 deleted").
183
dchill423169f262012-08-11 20:12:05 -0400184.. note:: Flash variables are prefaced with "flash\_" so avoid this prefix
185 in your own session names.
Derek Jones8ede1a22011-10-05 13:34:52 -0500186
187To add flashdata::
188
189 $this->session->set_flashdata('item', 'value');
190
191
192You can also pass an array to set_flashdata(), in the same manner as
193set_userdata().
194
195To read a flashdata variable::
196
197 $this->session->flashdata('item');
Johnathan Croom4beca5c2012-11-23 18:32:46 -0700198
Mike Funk7c26fab2012-02-24 09:45:02 -0500199An array of all flashdata can be retrieved as follows::
200
201 $this->session->all_flashdata();
Derek Jones8ede1a22011-10-05 13:34:52 -0500202
203
204If you find that you need to preserve a flashdata variable through an
205additional request, you can do so using the keep_flashdata() function.
Johnathan Croom4beca5c2012-11-23 18:32:46 -0700206You can either pass a single item or an array of flashdata items to keep.
Derek Jones8ede1a22011-10-05 13:34:52 -0500207
208::
209
210 $this->session->keep_flashdata('item');
Johnathan Croom4beca5c2012-11-23 18:32:46 -0700211 $this->session->keep_flashdata(array('item1', 'item2', 'item3'));
Derek Jones8ede1a22011-10-05 13:34:52 -0500212
dchill423169f262012-08-11 20:12:05 -0400213Tempdata
214========
215
216CodeIgniter also supports "tempdata", or session data with a specific
217expiration time. After the value expires, or the session expires or is
218deleted, the value is automatically removed.
219
220To add tempdata::
221
222 $expire = 300; // Expire in 5 minutes
223
224 $this->session->set_tempdata('item', 'value', $expire);
225
226You can also pass an array to set_tempdata()::
227
228 $tempdata = array('newuser' => TRUE, 'message' => 'Thanks for joining!');
229
230 $this->session->set_tempdata($tempdata, '', $expire);
231
232.. note:: If the expiration is omitted or set to 0, the default expiration of
233 5 minutes will be used.
234
235To read a tempdata variable::
236
237 $this->session->tempdata('item');
238
239If you need to remove a tempdata value before it expires,
240use unset_tempdata()::
241
242 $this->session->unset_tempdata('item');
243
244Destroying a Session
245====================
246
247To clear the current session::
248
249 $this->session->sess_destroy();
250
251.. note:: This function should be the last one called, and even flash
252 variables will no longer be available. If you only want some items
253 destroyed and not all, use unset_userdata().
254
255Session Preferences
256===================
257
258You'll find the following Session related preferences in your
259application/config/config.php file:
260
261=========================== =============== =========================== ==========================================================================
262Preference Default Options Description
263=========================== =============== =========================== ==========================================================================
264**sess_driver** cookie cookie/native/*custom* The initial session driver to load.
265**sess_valid_drivers** cookie, native None Additional valid drivers which may be loaded.
266**sess_cookie_name** ci_session None The name you want the session cookie saved as (data for Cookie driver or
267 session ID for Native driver).
268**sess_expiration** 7200 None The number of seconds you would like the session to last. The default
269 value is 2 hours (7200 seconds). If you would like a non-expiring
270 session set the value to zero: 0
271**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser
272 window is closed.
273**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data (Cookie driver only).
274**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the
275 table before enabling this option (Cookie driver only).
276**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table (Cookie driver only).
277**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself
278 and create a new session id.
279**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data.
280 Note that some ISPs dynamically changes the IP, so if you want a
281 non-expiring session you will likely set this to FALSE.
282**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data.
283=========================== =============== =========================== ==========================================================================
284
285In addition to the values above, the cookie and native drivers apply the
286following configuration values shared by the :doc:`Input <input>` and
287:doc:`Security <security>` classes:
288
289=========================== =============== ==========================================================================
290Preference Default Description
291=========================== =============== ==========================================================================
292**cookie_prefix** '' Set a cookie name prefix in order to avoid name collisions
293**cookie_domain** '' The domain for which the session is applicable
294**cookie_path** / The path to which the session is applicable
295=========================== =============== ==========================================================================
296
297Session Drivers
298===============
299
300By default, the `Cookie Driver`_ is loaded when a session is initialized.
301However, any valid driver may be selected with the $config['sess_driver']
302line in your config.php file.
303
304The session driver library comes with the cookie and native drivers
305installed, and `Custom Drivers`_ may also be installed by the user.
306
307Typically, only one driver will be used at a time, but CodeIgniter does
308support loading multiple drivers. If a specific valid driver is called, it
309will be automatically loaded. Or, an additional driver may be explicitly
310loaded by calling load_driver()::
311
312 $this->session->load_driver('native');
313
314The Session library keeps track of the most recently selected driver to call
315for driver methods. Normally, session class methods are called directly on
316the parent class, as illustrated above. However, any methods called through
317a specific driver will select that driver before invoking the parent method.
318
319So, alternation between multiple drivers can be achieved by specifying which
320driver to use for each call::
321
322 $this->session->native->set_userdata('foo', 'bar');
323
324 $this->session->cookie->userdata('foo');
325
326 $this->session->native->unset_userdata('foo');
327
328Notice in the previous example that the *native* userdata value 'foo'
329would be set to 'bar', which would NOT be returned by the call for
330the *cookie* userdata 'foo', nor would the *cookie* value be unset by
331the call to unset the *native* 'foo' value. The drivers maintain independent
332sets of values, regardless of key names.
333
334A specific driver may also be explicitly selected for use by pursuant
335methods with the select_driver() call::
336
337 $this->session->select_driver('native');
338
339 $this->session->userdata('item'); // Uses the native driver
340
341Cookie Driver
342-------------
343
344The Cookie driver stores session information for each user as serialized
345(and optionally encrypted) data in a cookie. It can also store the session
346data in a database table for added security, as this permits the session ID
347in the user's cookie to be matched against the stored session ID. By default
348only the cookie is saved. If you choose to use the database option you'll
349need to create the session table as indicated below.
350
351If you have the encryption option enabled, the serialized array will be
352encrypted before being stored in the cookie, making the data highly
353secure and impervious to being read or altered by someone. More info
354regarding encryption can be :doc:`found here <encryption>`, although
355the Session class will take care of initializing and encrypting the data
356automatically.
357
358.. note:: Even if you are not using encrypted sessions, you must set
359 an :doc:`encryption key <./encryption>` in your config file which is used
360 to aid in preventing session data manipulation.
361
362.. note:: Cookies can only hold 4KB of data, so be careful not to exceed
363 the capacity. The encryption process in particular produces a longer
364 data string than the original so keep careful track of how much data you
365 are storing.
Derek Jones8ede1a22011-10-05 13:34:52 -0500366
367Saving Session Data to a Database
dchill423169f262012-08-11 20:12:05 -0400368^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Derek Jones8ede1a22011-10-05 13:34:52 -0500369
370While the session data array stored in the user's cookie contains a
371Session ID, unless you store session data in a database there is no way
372to validate it. For some applications that require little or no
373security, session ID validation may not be needed, but if your
374application requires security, validation is mandatory. Otherwise, an
375old session could be restored by a user modifying their cookies.
376
377When session data is available in a database, every time a valid session
378is found in the user's cookie, a database query is performed to match
379it. If the session ID does not match, the session is destroyed. Session
380IDs can never be updated, they can only be generated when a new session
381is created.
382
383In order to store sessions, you must first create a database table for
384this purpose. Here is the basic prototype (for MySQL) required by the
Derek Jones4b83d912011-10-05 15:42:30 -0500385session class::
Derek Jones8ede1a22011-10-05 13:34:52 -0500386
Derek Jones4b83d912011-10-05 15:42:30 -0500387 CREATE TABLE IF NOT EXISTS `ci_sessions` (
388 session_id varchar(40) DEFAULT '0' NOT NULL,
Andrey Andreev5a257182012-06-10 06:18:14 +0300389 ip_address varchar(45) DEFAULT '0' NOT NULL,
Derek Jones4b83d912011-10-05 15:42:30 -0500390 user_agent varchar(120) NOT NULL,
391 last_activity int(10) unsigned DEFAULT 0 NOT NULL,
392 user_data text NOT NULL,
Andrey Andreeve2afc882012-11-01 01:35:34 +0200393 PRIMARY KEY (session_id, ip_address, user_agent),
Derek Jones4b83d912011-10-05 15:42:30 -0500394 KEY `last_activity_idx` (`last_activity`)
395 );
Derek Jones8ede1a22011-10-05 13:34:52 -0500396
397.. note:: By default the table is called ci_sessions, but you can name
398 it anything you want as long as you update the
399 application/config/config.php file so that it contains the name you have
400 chosen. Once you have created your database table you can enable the
401 database option in your config.php file as follows::
402
403 $config['sess_use_database'] = TRUE;
404
405 Once enabled, the Session class will store session data in the DB.
406
407 Make sure you've specified the table name in your config file as well::
408
409 $config['sess_table_name'] = 'ci_sessions';
410
dchill423169f262012-08-11 20:12:05 -0400411.. note:: The Cookie driver has built-in garbage collection which clears
Derek Jones8ede1a22011-10-05 13:34:52 -0500412 out expired sessions so you do not need to write your own routine to do
413 it.
414
dchill423169f262012-08-11 20:12:05 -0400415Native Driver
416-------------
Derek Jones8ede1a22011-10-05 13:34:52 -0500417
dchill423169f262012-08-11 20:12:05 -0400418The Native driver relies on native PHP sessions to store data in the
419$_SESSION superglobal array. All stored values continue to be available
420through $_SESSION, but flash- and temp- data items carry special prefixes.
Derek Jones8ede1a22011-10-05 13:34:52 -0500421
dchill423169f262012-08-11 20:12:05 -0400422Custom Drivers
423--------------
Derek Jones8ede1a22011-10-05 13:34:52 -0500424
dchill423169f262012-08-11 20:12:05 -0400425You may also :doc:`create your own <../general/creating_drivers>` custom
426session drivers. A session driver basically manages an array of name/value
427pairs with some sort of storage mechanism.
Derek Jones8ede1a22011-10-05 13:34:52 -0500428
dchill42b3816b72012-08-13 09:47:58 -0400429To make a new driver, extend CI_Session_driver. Overload the initialize()
dchill423169f262012-08-11 20:12:05 -0400430method and read or create session data. Then implement a save handler to
431write changed data to storage (sess_save), a destroy handler to remove
dchill42b3816b72012-08-13 09:47:58 -0400432deleted data (sess_destroy), a regenerate handler to make a new session ID
433(sess_regenerate), and an access handler to expose the data (get_userdata).
434Your initial class might look like::
Derek Jones8ede1a22011-10-05 13:34:52 -0500435
dchill423169f262012-08-11 20:12:05 -0400436 class CI_Session_custom extends CI_Session_driver {
437 protected function initialize()
438 {
439 // Read existing session data or create a new one
440 }
Derek Jones8ede1a22011-10-05 13:34:52 -0500441
dchill423169f262012-08-11 20:12:05 -0400442 public function sess_save()
443 {
444 // Save current data to storage
445 }
446
447 public function sess_destroy()
448 {
449 // Destroy the current session and clean up storage
450 }
451
452 public function sess_regenerate()
453 {
454 // Create new session ID
455 }
456
457 public function &get_userdata()
458 {
459 // Return a reference to your userdata array
460 }
461 }
462
463Notice that get_userdata() returns a reference so the parent library is
464accessing the same array the driver object is using. This saves memory
465and avoids synchronization issues during usage.
466
467Put your driver in the libraries/Session/drivers folder anywhere in your
468package paths. This includes the application directory, the system directory,
469or any path you add with $CI->load->add_package_path(). Your driver must be
470named CI_Session_<name>, and your filename must be Session_<name>.php,
471preferably also capitalized, such as::
472
473 CI_Session_foo in libraries/Session/drivers/Session_foo.php
474
475Then specify the driver by setting 'sess_driver' in your config.php file or as a
476parameter when loading the CI_Session object::
477
478 $config['sess_driver'] = 'foo';
479
480OR::
481
482 $CI->load->driver('session', array('sess_driver' => 'foo'));
483
484The driver specified by 'sess_driver' is automatically included as a valid
485driver. However, if you want to make a custom driver available as an option
486without making it the initially loaded driver, set 'sess_valid_drivers' in
487your config.php file to an array including your driver name::
488
489 $config['sess_valid_drivers'] = array('sess_driver');
490