blob: dfb732491036cf7884e48945cf08a6b4c476aec7 [file] [log] [blame]
Derek Allard2067d1a2008-11-13 22:59:24 +00001<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
3<head>
4
5<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6<title>Session Class : CodeIgniter User Guide</title>
7
8<style type='text/css' media='all'>@import url('../userguide.css');</style>
9<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
10
11<script type="text/javascript" src="../nav/nav.js"></script>
12<script type="text/javascript" src="../nav/prototype.lite.js"></script>
13<script type="text/javascript" src="../nav/moo.fx.js"></script>
14<script type="text/javascript" src="../nav/user_guide_menu.js"></script>
15
16<meta http-equiv='expires' content='-1' />
17<meta http-equiv= 'pragma' content='no-cache' />
18<meta name='robots' content='all' />
19<meta name='author' content='ExpressionEngine Dev Team' />
20<meta name='description' content='CodeIgniter User Guide' />
21
22</head>
23<body>
24
25<!-- START NAVIGATION -->
26<div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div>
27<div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div>
28<div id="masthead">
29<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
30<tr>
Phil Sturgeon9c63d0b2011-10-27 01:55:44 +010031<td><h1>CodeIgniter User Guide Version 2.1.0</h1></td>
Derek Allard2067d1a2008-11-13 22:59:24 +000032<td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td>
33</tr>
34</table>
35</div>
36<!-- END NAVIGATION -->
37
38
39<!-- START BREADCRUMB -->
40<table cellpadding="0" cellspacing="0" border="0" style="width:100%">
41<tr>
42<td id="breadcrumb">
43<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
44<a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp;
45Session Class
46</td>
47<td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td>
48</tr>
49</table>
50<!-- END BREADCRUMB -->
51
52<br clear="all" />
53
54
55<!-- START CONTENT -->
56<div id="content">
57
58
59<h1>Session Class</h1>
60
61<p>The Session class permits you maintain a user's "state" and track their activity while they browse your site.
62The Session class stores session information for each user as serialized (and optionally encrypted) data in a cookie.
63It can also store the session data in a database table for added security, as this permits the session ID in the
Derek Jones4b9c6292011-07-01 17:40:48 -050064user's cookie to be matched against the stored session ID. By default only the cookie is saved. If you choose to
Derek Allard2067d1a2008-11-13 22:59:24 +000065use the database option you'll need to create the session table as indicated below.
66</p>
67
68<p class="important"><strong>Note:</strong> The Session class does <strong>not</strong> utilize native PHP sessions. It
69generates its own session data, offering more flexibility for developers.</p>
70
Derek Jones5485db52010-08-30 21:31:08 -050071<p class="important"><strong>Note:</strong> Even if you are not using encrypted sessions, you must set
Derek Jones52ace432010-08-30 21:33:38 -050072an <a href="./encryption.html">encryption key</a> in your config file which is used to aid in preventing session data manipulation.</p>
Derek Jones5485db52010-08-30 21:31:08 -050073
Derek Allard2067d1a2008-11-13 22:59:24 +000074<h2>Initializing a Session</h2>
75
76<p>Sessions will typically run globally with each page load, so the session class must either be
77<a href="../general/libraries.html">initialized</a> in your
78<a href="../general/controllers.html">controller</a> constructors, or it can be
79<a href="../general/autoloader.html">auto-loaded</a> by the system.
80For the most part the session class will run unattended in the background, so simply initializing the class
81will cause it to read, create, and update sessions.</p>
82
83
84<p>To initialize the Session class manually in your controller constructor, use the <dfn>$this->load->library</dfn> function:</p>
85
86<code>$this->load->library('session');</code>
87<p>Once loaded, the Sessions library object will be available using: <dfn>$this->session</dfn></p>
88
89
90<h2>How do Sessions work?</h2>
91
92<p>When a page is loaded, the session class will check to see if valid session data exists in the user's session cookie.
93If sessions data does <strong>not</strong> exist (or if it has expired) a new session will be created and saved in the cookie.
94If a session does exist, its information will be updated and the cookie will be updated. With each update, the session_id will be regenerated.</p>
95
Derek Jones4b9c6292011-07-01 17:40:48 -050096<p>It's important for you to understand that once initialized, the Session class runs automatically. There is nothing
97you need to do to cause the above behavior to happen. You can, as you'll see below, work with session data or
Derek Allard2067d1a2008-11-13 22:59:24 +000098even add your own data to a user's session, but the process of reading, writing, and updating a session is automatic.</p>
99
100
101<h2>What is Session Data?</h2>
102
103<p>A <em>session</em>, as far as CodeIgniter is concerned, is simply an array containing the following information:</p>
104
105<ul>
106<li>The user's unique Session ID (this is a statistically random string with very strong entropy, hashed with MD5 for portability, and regenerated (by default) every five minutes)</li>
107<li>The user's IP Address</li>
Derek Jones806b8242011-06-22 06:50:48 -0500108<li>The user's User Agent data (the first 120 characters of the browser data string)</li>
Razican114ab092011-04-25 17:26:45 +0200109<li>The "last activity" time stamp.</li>
Derek Allard2067d1a2008-11-13 22:59:24 +0000110</ul>
111
112<p>The above data is stored in a cookie as a serialized array with this prototype:</p>
113
114<code>[array]<br />
115(<br />
116&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'session_id'&nbsp;&nbsp;&nbsp;&nbsp;=> random hash,<br />
117&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ip_address'&nbsp;&nbsp;&nbsp;&nbsp;=> 'string - user IP address',<br />
118&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'user_agent'&nbsp;&nbsp;&nbsp;&nbsp;=> 'string - user agent data',<br />
119&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'last_activity' => timestamp<br />
120)</code>
121
122<p>If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie,
123making the data highly secure and impervious to being read or altered by someone. More info regarding encryption
124can be <a href="encryption.html">found here</a>, although the Session class will take care of initializing
125and encrypting the data automatically.</p>
126
Derek Jones4b9c6292011-07-01 17:40:48 -0500127<p>Note: Session cookies are only updated every five minutes by default to reduce processor load. If you repeatedly reload a page
Derek Allard2067d1a2008-11-13 22:59:24 +0000128you'll notice that the "last activity" time only updates if five minutes or more has passed since the last time
Derek Allard563885b2010-01-17 07:31:03 +0000129the cookie was written. This time is configurable by changing the $config['sess_time_to_update'] line in your system/config/config.php file.</p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000130
131<h2>Retrieving Session Data</h2>
132
133<p>Any piece of information from the session array is available using the following function:</p>
134
135<code>$this->session->userdata('<samp>item</samp>');</code>
136
Derek Jones4b9c6292011-07-01 17:40:48 -0500137<p>Where <samp>item</samp> is the array index corresponding to the item you wish to fetch. For example, to fetch the session ID you
Derek Allard2067d1a2008-11-13 22:59:24 +0000138will do this:</p>
139
140<code>$session_id = $this->session->userdata('<samp>session_id</samp>');</code>
141
142<p><strong>Note:</strong> The function returns FALSE (boolean) if the item you are trying to access does not exist.</p>
143
144
145<h2>Adding Custom Session Data</h2>
146
147<p>A useful aspect of the session array is that you can add your own data to it and it will be stored in the user's cookie.
Derek Jones4b9c6292011-07-01 17:40:48 -0500148Why would you want to do this? Here's one example:</p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000149
150<p>Let's say a particular user logs into your site. Once authenticated,
151you could add their username and email address to the session cookie, making that data globally available to you without
152having to run a database query when you need it.</p>
153
154<p>To add your data to the session array involves passing an array containing your new data to this function:</p>
155
156<code>$this->session->set_userdata(<samp>$array</samp>);</code>
157
Derek Jones4b9c6292011-07-01 17:40:48 -0500158<p>Where <samp>$array</samp> is an associative array containing your new data. Here's an example:</p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000159
160
161<p><code>$newdata = array(<br />
162 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'username'&nbsp; => 'johndoe',<br />
163 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'email'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=> 'johndoe@some-site.com',<br />
164 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'logged_in' => TRUE<br />
165 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br />
166 <br />
167 $this->session->set_userdata(<samp>$newdata</samp>);</code></p>
168<p>If you want to add userdata one value at a time, set_userdata() also supports this syntax. </p>
169<p><code>$this-&gt;session-&gt;set_userdata('some_name', 'some_value');</code></p>
Derek Jones4b9c6292011-07-01 17:40:48 -0500170<p class="important"><strong>Note:</strong> Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The
Derek Allard2067d1a2008-11-13 22:59:24 +0000171encryption process in particular produces a longer data string than the original so keep careful track of how much data you are storing.</p>
172
Greg Aker34033662011-04-18 11:18:09 -0500173<h2>Retrieving All Session Data</h2>
174<p>An array of all userdata can be retrieved as follows:</p>
175<code>$this-&gt;session-&gt;all_userdata()</code>
176
177<p>And returns an associative array like the following:</p>
178
179<pre>
180Array
181(
Derek Jones4b9c6292011-07-01 17:40:48 -0500182 [session_id] => 4a5a5dca22728fb0a84364eeb405b601
183 [ip_address] => 127.0.0.1
184 [user_agent] => Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7;
185 [last_activity] => 1303142623
Greg Aker34033662011-04-18 11:18:09 -0500186)
187</pre>
188
189
Derek Allard2067d1a2008-11-13 22:59:24 +0000190<h2>Removing Session Data</h2>
191<p>Just as set_userdata() can be used to add information into a session, unset_userdata() can be used to remove it, by passing the session key. For example, if you wanted to remove 'some_name' from your session information: </p>
192<p><code>$this-&gt;session-&gt;unset_userdata('some_name');</code></p>
193<p>This function can also be passed an associative array of items to unset.</p>
194<p><code>$array_items = array('username' => '', 'email' => '');<br />
195<br />
196$this-&gt;session-&gt;unset_userdata(<samp>$array_items</samp>);</code></p>
197<h2>Flashdata</h2>
198<p>CodeIgniter supports &quot;flashdata&quot;, or session data that will only be available for the next server request, and are then automatically cleared. These can be very useful, and are typically used for informational or status messages (for example: &quot;record 2 deleted&quot;).</p>
199<p>Note: Flash variables are prefaced with &quot;flash_&quot; so avoid this prefix in your own session names.</p>
200<p>To add flashdata:</p>
201<p><code>$this-&gt;session-&gt;set_flashdata('item', 'value');</code></p>
202<p>You can also pass an array to set_flashdata(), in the same manner as set_userdata(). </p>
203<p>To read a flashdata variable:</p>
204<p><code>$this-&gt;session-&gt;flashdata('item');</code></p>
205<p>If you find that you need to preserve a flashdata variable through an additional request, you can do so using the keep_flashdata() function.</p>
206<p><code>$this-&gt;session-&gt;keep_flashdata('item');</code></p>
207<h2>Saving Session Data to a Database</h2>
208<p>While the session data array stored in the user's cookie contains a Session ID,
Derek Jones4b9c6292011-07-01 17:40:48 -0500209unless you store session data in a database there is no way to validate it. For some applications that require little or no
210security, session ID validation may not be needed, but if your application requires security, validation is mandatory. Otherwise, an old session
Derek Jones95e05a02010-09-02 10:20:54 -0500211could be restored by a user modifying their cookies.</p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000212
213<p>When session data is available in a database, every time a valid session is found in the user's cookie, a database
Derek Jones4b9c6292011-07-01 17:40:48 -0500214query is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never
Derek Allard2067d1a2008-11-13 22:59:24 +0000215be updated, they can only be generated when a new session is created.</p>
216
Derek Jones95e05a02010-09-02 10:20:54 -0500217
Derek Jones4b9c6292011-07-01 17:40:48 -0500218<p>In order to store sessions, you must first create a database table for this purpose. Here is the basic
Derek Allard2067d1a2008-11-13 22:59:24 +0000219prototype (for MySQL) required by the session class:</p>
220
Greg Aker882b76b2011-04-20 11:22:09 -0500221<textarea class="textarea" style="width:100%" cols="50" rows="10">
Derek Jones4b9c6292011-07-01 17:40:48 -0500222CREATE TABLE IF NOT EXISTS `ci_sessions` (
Greg Aker882b76b2011-04-20 11:22:09 -0500223 session_id varchar(40) DEFAULT '0' NOT NULL,
224 ip_address varchar(16) DEFAULT '0' NOT NULL,
Greg Aker50671cf2011-04-20 11:36:45 -0500225 user_agent varchar(120) NOT NULL,
Greg Aker882b76b2011-04-20 11:22:09 -0500226 last_activity int(10) unsigned DEFAULT 0 NOT NULL,
227 user_data text NOT NULL,
228 PRIMARY KEY (session_id),
229 KEY `last_activity_idx` (`last_activity`)
230);
231</textarea>
Derek Allard2067d1a2008-11-13 22:59:24 +0000232
233<p><strong>Note:</strong> By default the table is called <dfn>ci_sessions</dfn>, but you can name it anything you want
234as long as you update the <kbd>application/config/config.php</kbd> file so that it contains the name you have chosen.
235Once you have created your database table you can enable the database option in your config.php file as follows:</p>
236
237<code>$config['sess_use_database'] = TRUE;</code>
238
239<p>Once enabled, the Session class will store session data in the DB.</p>
240
241<p>Make sure you've specified the table name in your config file as well:</p>
242
Derek Allard9a42f582010-07-13 09:41:11 -0400243<code>$config['sess_table_name'] = 'ci_sessions';</code>
Derek Allard2067d1a2008-11-13 22:59:24 +0000244
245<p class="important"><strong>Note:</strong> The Session class has built-in garbage collection which clears out expired sessions so you
246do not need to write your own routine to do it.</p>
247
248
249<h2>Destroying a Session </h2>
250<p>To clear the current session: </p>
251<code>$this-&gt;session-&gt;sess_destroy();</code>
Derek Jones4b9c6292011-07-01 17:40:48 -0500252<p class="important"><strong>Note:</strong> This function should be the last one called, and even flash variables will no longer be available. If you only want some items destroyed and not all, use <dfn>unset_userdata()</dfn>.</p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000253
254
255
256<h2>Session Preferences</h2>
257<p>You'll find the following Session related preferences in your <kbd>application/config/config.php</kbd> file:</p>
258
259
260<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
261<tr>
262 <th>Preference</th>
263 <th>Default</th>
264 <th>Options</th>
265 <th>Description</th>
266</tr>
267<tr>
268 <td class="td"><strong>sess_cookie_name</strong></td>
269 <td class="td">ci_session</td>
270 <td class="td">None</td>
271 <td class="td">The name you want the session cookie saved as.</td>
272</tr>
273<tr>
274 <td class="td"><strong>sess_expiration</strong></td>
275 <td class="td">7200</td>
276 <td class="td">None</td>
277 <td class="td">The number of seconds you would like the session to last. The default value is 2 hours (7200 seconds). If you would like a non-expiring session set the value to zero: 0</td>
278</tr>
279<tr>
Derek Joneseaa71ba2010-09-02 10:32:07 -0500280 <td class="td"><strong>sess_expire_on_close</strong></td>
281 <td class="td">FALSE</td>
282 <td class="td">TRUE/FALSE (boolean)</td>
283 <td class="td">Whether to cause the session to expire automatically when the browser window is closed.</td>
284</tr>
285<tr>
Derek Allard2067d1a2008-11-13 22:59:24 +0000286 <td class="td"><strong>sess_encrypt_cookie</strong></td>
287 <td class="td">FALSE</td>
288 <td class="td">TRUE/FALSE (boolean)</td>
289 <td class="td">Whether to encrypt the session data.</td>
290</tr>
291<tr>
292 <td class="td"><strong>sess_use_database</strong></td>
293 <td class="td">FALSE</td>
294 <td class="td">TRUE/FALSE (boolean)</td>
Derek Jones4b9c6292011-07-01 17:40:48 -0500295 <td class="td">Whether to save the session data to a database. You must create the table before enabling this option.</td>
Derek Allard2067d1a2008-11-13 22:59:24 +0000296</tr>
297<tr>
298 <td class="td"><strong>sess_table_name</strong></td>
299 <td class="td">ci_sessions</td>
300 <td class="td">Any valid SQL table name</td>
301 <td class="td">The name of the session database table.</td>
302</tr>
303<tr>
304 <td class="td"><strong>sess_time_to_update</strong></td>
305 <td class="td">300</td>
306 <td class="td">Time in seconds</td>
307 <td class="td">This options controls how often the session class will regenerate itself and create a new session id.</td>
308</tr>
309<tr>
310 <td class="td"><strong>sess_match_ip</strong></td>
311 <td class="td">FALSE</td>
312 <td class="td">TRUE/FALSE (boolean)</td>
Derek Jones4b9c6292011-07-01 17:40:48 -0500313 <td class="td">Whether to match the user's IP address when reading the session data. Note that some ISPs dynamically
Derek Allard2067d1a2008-11-13 22:59:24 +0000314 changes the IP, so if you want a non-expiring session you will likely set this to FALSE.</td>
315</tr>
316<tr>
317 <td class="td"><strong>sess_match_useragent</strong></td>
318 <td class="td">TRUE</td>
319 <td class="td">TRUE/FALSE (boolean)</td>
320 <td class="td">Whether to match the User Agent when reading the session data.</td>
321</tr>
322</table>
323
324
325</div>
326<!-- END CONTENT -->
327
328
329<div id="footer">
330<p>
Derek Jones9898b892010-03-10 14:04:17 -0600331Previous Topic:&nbsp;&nbsp;<a href="security.html">Security Class</a>
Derek Allard2067d1a2008-11-13 22:59:24 +0000332&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
333<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
334<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
335Next Topic:&nbsp;&nbsp;<a href="trackback.html">Trackback Class</a>
336</p>
Derek Jones898949f2011-01-28 07:42:16 -0600337<p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2011 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p>
Derek Allard2067d1a2008-11-13 22:59:24 +0000338</div>
339
340</body>
adminb0dd10f2006-08-25 17:25:49 +0000341</html>