blob: ef32f5d71bae5c78f7b25f273cbe6c3250709bf5 [file] [log] [blame]
Derek Jones8ede1a22011-10-05 13:34:52 -05001#############
2Session Class
3#############
4
5The Session class permits you maintain a user's "state" and track their
6activity while they browse your site. The Session class stores session
7information for each user as serialized (and optionally encrypted) data
8in a cookie. It can also store the session data in a database table for
9added security, as this permits the session ID in the user's cookie to
10be matched against the stored session ID. By default only the cookie is
11saved. If you choose to use the database option you'll need to create
12the session table as indicated below.
13
14.. note:: The Session class does **not** utilize native PHP sessions. It
15 generates its own session data, offering more flexibility for
16 developers.
17
18.. note:: Even if you are not using encrypted sessions, you must set
19 an :doc:`encryption key <./encryption>` in your config file which is used
20 to aid in preventing session data manipulation.
21
22Initializing a Session
23======================
24
25Sessions will typically run globally with each page load, so the session
26class must either be :doc:`initialized <../general/libraries>` in your
27:doc:`controller <../general/controllers>` constructors, or it can be
28:doc:`auto-loaded <../general/autoloader>` by the system. For the most
29part the session class will run unattended in the background, so simply
30initializing the class will cause it to read, create, and update
31sessions.
32
33To initialize the Session class manually in your controller constructor,
34use the $this->load->library function::
35
36 $this->load->library('session');
37
38Once loaded, the Sessions library object will be available using:
39$this->session
40
41How do Sessions work?
42=====================
43
44When a page is loaded, the session class will check to see if valid
45session data exists in the user's session cookie. If sessions data does
46**not** exist (or if it has expired) a new session will be created and
47saved in the cookie. If a session does exist, its information will be
48updated and the cookie will be updated. With each update, the
49session_id will be regenerated.
50
51It's important for you to understand that once initialized, the Session
52class runs automatically. There is nothing you need to do to cause the
53above behavior to happen. You can, as you'll see below, work with
54session data or even add your own data to a user's session, but the
55process of reading, writing, and updating a session is automatic.
56
57What is Session Data?
58=====================
59
60A *session*, as far as CodeIgniter is concerned, is simply an array
61containing the following information:
62
63- The user's unique Session ID (this is a statistically random string
64 with very strong entropy, hashed with MD5 for portability, and
65 regenerated (by default) every five minutes)
66- The user's IP Address
67- The user's User Agent data (the first 120 characters of the browser
68 data string)
69- The "last activity" time stamp.
70
71The above data is stored in a cookie as a serialized array with this
72prototype::
73
Derek Jones4b83d912011-10-05 15:42:30 -050074 [array]
75 (
76 'session_id' => random hash,
77 'ip_address' => 'string - user IP address',
78 'user_agent' => 'string - user agent data',
79 'last_activity' => timestamp
80 )
Derek Jones8ede1a22011-10-05 13:34:52 -050081
82If you have the encryption option enabled, the serialized array will be
83encrypted before being stored in the cookie, making the data highly
84secure and impervious to being read or altered by someone. More info
85regarding encryption can be :doc:`found here <encryption>`, although
86the Session class will take care of initializing and encrypting the data
87automatically.
88
89Note: Session cookies are only updated every five minutes by default to
90reduce processor load. If you repeatedly reload a page you'll notice
91that the "last activity" time only updates if five minutes or more has
92passed since the last time the cookie was written. This time is
93configurable by changing the $config['sess_time_to_update'] line in
94your system/config/config.php file.
95
96Retrieving Session Data
97=======================
98
99Any piece of information from the session array is available using the
100following function::
101
102 $this->session->userdata('item');
103
104Where item is the array index corresponding to the item you wish to
105fetch. For example, to fetch the session ID you will do this::
106
107 $session_id = $this->session->userdata('session_id');
108
109.. note:: The function returns FALSE (boolean) if the item you are
110 trying to access does not exist.
111
112Adding Custom Session Data
113==========================
114
115A useful aspect of the session array is that you can add your own data
116to it and it will be stored in the user's cookie. Why would you want to
117do this? Here's one example:
118
119Let's say a particular user logs into your site. Once authenticated, you
120could add their username and email address to the session cookie, making
121that data globally available to you without having to run a database
122query when you need it.
123
124To add your data to the session array involves passing an array
125containing your new data to this function::
126
127 $this->session->set_userdata($array);
128
129Where $array is an associative array containing your new data. Here's an
130example::
131
Derek Jones4b83d912011-10-05 15:42:30 -0500132 $newdata = array(
133 'username' => 'johndoe',
134 'email' => 'johndoe@some-site.com',
135 'logged_in' => TRUE
136 );
Derek Jones8ede1a22011-10-05 13:34:52 -0500137
Derek Jones4b83d912011-10-05 15:42:30 -0500138 $this->session->set_userdata($newdata);
Derek Jones8ede1a22011-10-05 13:34:52 -0500139
140If you want to add userdata one value at a time, set_userdata() also
141supports this syntax.
142
143::
144
145 $this->session->set_userdata('some_name', 'some_value');
146
147
148.. note:: Cookies can only hold 4KB of data, so be careful not to exceed
149 the capacity. The encryption process in particular produces a longer
150 data string than the original so keep careful track of how much data you
151 are storing.
152
153Retrieving All Session Data
154===========================
155
156An array of all userdata can be retrieved as follows::
157
158 $this->session->all_userdata()
159
160And returns an associative array like the following::
161
Derek Jones4b83d912011-10-05 15:42:30 -0500162 Array
163 (
164 [session_id] => 4a5a5dca22728fb0a84364eeb405b601
165 [ip_address] => 127.0.0.1
166 [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
167 [last_activity] => 1303142623
168 )
Derek Jones8ede1a22011-10-05 13:34:52 -0500169
170Removing Session Data
171=====================
172
173Just as set_userdata() can be used to add information into a session,
174unset_userdata() can be used to remove it, by passing the session key.
175For example, if you wanted to remove 'some_name' from your session
176information::
177
178 $this->session->unset_userdata('some_name');
179
180
181This function can also be passed an associative array of items to unset.
182
183::
184
Derek Jones4b83d912011-10-05 15:42:30 -0500185 $array_items = array('username' => '', 'email' => '');
186
187 $this->session->unset_userdata($array_items);
Derek Jones8ede1a22011-10-05 13:34:52 -0500188
189
190Flashdata
191=========
192
193CodeIgniter supports "flashdata", or session data that will only be
194available for the next server request, and are then automatically
195cleared. These can be very useful, and are typically used for
196informational or status messages (for example: "record 2 deleted").
197
198Note: Flash variables are prefaced with "flash\_" so avoid this prefix
199in your own session names.
200
201To add flashdata::
202
203 $this->session->set_flashdata('item', 'value');
204
205
206You can also pass an array to set_flashdata(), in the same manner as
207set_userdata().
208
209To read a flashdata variable::
210
211 $this->session->flashdata('item');
212
213
214If you find that you need to preserve a flashdata variable through an
215additional request, you can do so using the keep_flashdata() function.
216
217::
218
219 $this->session->keep_flashdata('item');
220
221
222Saving Session Data to a Database
223=================================
224
225While the session data array stored in the user's cookie contains a
226Session ID, unless you store session data in a database there is no way
227to validate it. For some applications that require little or no
228security, session ID validation may not be needed, but if your
229application requires security, validation is mandatory. Otherwise, an
230old session could be restored by a user modifying their cookies.
231
232When session data is available in a database, every time a valid session
233is found in the user's cookie, a database query is performed to match
234it. If the session ID does not match, the session is destroyed. Session
235IDs can never be updated, they can only be generated when a new session
236is created.
237
238In order to store sessions, you must first create a database table for
239this purpose. Here is the basic prototype (for MySQL) required by the
Derek Jones4b83d912011-10-05 15:42:30 -0500240session class::
Derek Jones8ede1a22011-10-05 13:34:52 -0500241
Derek Jones4b83d912011-10-05 15:42:30 -0500242 CREATE TABLE IF NOT EXISTS `ci_sessions` (
243 session_id varchar(40) DEFAULT '0' NOT NULL,
244 ip_address varchar(16) DEFAULT '0' NOT NULL,
245 user_agent varchar(120) NOT NULL,
246 last_activity int(10) unsigned DEFAULT 0 NOT NULL,
247 user_data text NOT NULL,
248 PRIMARY KEY (session_id),
249 KEY `last_activity_idx` (`last_activity`)
250 );
Derek Jones8ede1a22011-10-05 13:34:52 -0500251
252.. note:: By default the table is called ci_sessions, but you can name
253 it anything you want as long as you update the
254 application/config/config.php file so that it contains the name you have
255 chosen. Once you have created your database table you can enable the
256 database option in your config.php file as follows::
257
258 $config['sess_use_database'] = TRUE;
259
260 Once enabled, the Session class will store session data in the DB.
261
262 Make sure you've specified the table name in your config file as well::
263
264 $config['sess_table_name'] = 'ci_sessions';
265
266.. note:: The Session class has built-in garbage collection which clears
267 out expired sessions so you do not need to write your own routine to do
268 it.
269
270Destroying a Session
271====================
272
273To clear the current session::
274
275 $this->session->sess_destroy();
276
277.. note:: This function should be the last one called, and even flash
278 variables will no longer be available. If you only want some items
279 destroyed and not all, use unset_userdata().
280
281Session Preferences
282===================
283
284You'll find the following Session related preferences in your
285application/config/config.php file:
286
Joseph Wensley5b3ea1a2011-10-06 20:54:32 -0400287=========================== =============== =========================== ==========================================================================
288Preference Default Options Description
289=========================== =============== =========================== ==========================================================================
290**sess_cookie_name** ci_session None The name you want the session cookie saved as.
291**sess_expiration** 7200 None The number of seconds you would like the session to last. The default
292 value is 2 hours (7200 seconds). If you would like a non-expiring
293 session set the value to zero: 0
294**sess_expire_on_close** FALSE TRUE/FALSE (boolean) Whether to cause the session to expire automatically when the browser
295 window is closed.
296**sess_encrypt_cookie** FALSE TRUE/FALSE (boolean) Whether to encrypt the session data.
297**sess_use_database** FALSE TRUE/FALSE (boolean) Whether to save the session data to a database. You must create the
298 table before enabling this option.
299**sess_table_name** ci_sessions Any valid SQL table name The name of the session database table.
300**sess_time_to_update** 300 Time in seconds This options controls how often the session class will regenerate itself
301 and create a new session id.
302**sess_match_ip** FALSE TRUE/FALSE (boolean) Whether to match the user's IP address when reading the session data.
303 Note that some ISPs dynamically changes the IP, so if you want a
304 non-expiring session you will likely set this to FALSE.
305**sess_match_useragent** TRUE TRUE/FALSE (boolean) Whether to match the User Agent when reading the session data.
306=========================== =============== =========================== ==========================================================================