blob: 312f71547104dce717c2cc96d42e4d2b4d9d33a2 [file] [log] [blame]
Derek Allard309d63f2007-08-17 11:49:29 +00001<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Derek Allardafd99ac2008-01-19 19:59:14 +00002<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
Derek Allard309d63f2007-08-17 11:49:29 +00003<head>
4
5<title>CodeIgniter User Guide</title>
6
7<style type='text/css' media='all'>@import url('../userguide.css');</style>
8<link rel='stylesheet' type='text/css' media='all' href='../userguide.css' />
9
10<script type="text/javascript" src="../nav/nav.js"></script>
11<script type="text/javascript" src="../nav/prototype.lite.js"></script>
12<script type="text/javascript" src="../nav/moo.fx.js"></script>
Derek Allardb3412372007-10-25 12:15:16 +000013<script type="text/javascript" src="../nav/user_guide_menu.js"></script>
Derek Allard309d63f2007-08-17 11:49:29 +000014
15<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
16<meta http-equiv='expires' content='-1' />
17<meta http-equiv= 'pragma' content='no-cache' />
18<meta name='robots' content='all' />
Derek Allard3d879d52008-01-18 19:41:32 +000019<meta name='author' content='ExpressionEngine Dev Team' />
Derek Allard309d63f2007-08-17 11:49:29 +000020<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.jpg" width="153" height="44" 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>
Derek Allard067f2cc2008-02-04 22:12:03 +000031<td><h1>CodeIgniter User Guide Version 1.6.1</h1></td>
Derek Allard309d63f2007-08-17 11:49:29 +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">
Derek Jones7a9193a2008-01-21 18:39:20 +000043<a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp;
Derek Allard309d63f2007-08-17 11:49:29 +000044<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
64user's cookie to be matched against the stored session ID. By default only the cookie is saved. If you choose to
65use 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
71<h2>Initializing a Session</h2>
72
73<p>Sessions will typically run globally with each page load, so the session class must either be
74<a href="../general/libraries.html">initialized</a> in your
75<a href="../general/controllers.html">controller</a> constructors, or it can be
76<a href="../general/autoloader.html">auto-loaded</a> by the system.
77For the most part the session class will run unattended in the background, so simply initializing the class
78will cause it to read, create, and update sessions.</p>
79
80
81<p>To initialize the Session class manually in your controller constructor, use the <dfn>$this->load->library</dfn> function:</p>
82
83<code>$this->load->library('session');</code>
84<p>Once loaded, the Sessions library object will be available using: <dfn>$this->session</dfn></p>
85
86
87<h2>How do Sessions work?</h2>
88
89<p>When a page is loaded, the session class will check to see if valid session data exists in the user's session cookie.
90If sessions data does <strong>not</strong> exist (or if it has expired) a new session will be created and saved in the cookie.
91If 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>
92
93<p>It's important for you to understand that once initialized, the Session class runs automatically. There is nothing
94you need to do to cause the above behavior to happen. You can, as you'll see below, work with session data or
95even add your own data to a user's session, but the process of reading, writing, and updating a session is automatic.</p>
96
97
98<h2>What is Session Data?</h2>
99
100<p>A <em>session</em>, as far as CodeIgniter is concerned, is simply an array containing the following information:</p>
101
102<ul>
103<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>
104<li>The user's IP Address</li>
105<li>The user's User Agent data (the first 50 characters of the browser data string)</li>
106<li>The "last activity" and "last visit" time stamps.</li>
107</ul>
108
109<p>The above data is stored in a cookie as a serialized array with this prototype:</p>
110
111<code>[array]<br />
112(<br />
113&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'session_id'&nbsp;&nbsp;&nbsp;&nbsp;=> random hash,<br />
114&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'ip_address'&nbsp;&nbsp;&nbsp;&nbsp;=> 'string - user IP address',<br />
115&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'user_agent'&nbsp;&nbsp;&nbsp;&nbsp;=> 'string - user agent data',<br />
116&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'last_activity' => timestamp,<br />
117&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'last_visit'&nbsp;&nbsp;&nbsp;&nbsp;=> timestamp<br />
118)</code>
119
120<p>If you have the encryption option enabled, the serialized array will be encrypted before being stored in the cookie,
121making the data highly secure and impervious to being read or altered by someone. More info regarding encryption
122can be <a href="encryption.html">found here</a>, although the Session class will take care of initializing
123and encrypting the data automatically.</p>
124
125<p>Note: Session cookies are only updated every five minutes by default to reduce processor load. If you repeatedly reload a page
126you'll notice that the "last activity" time only updates if five minutes or more has passed since the last time
127the cookie was written. This time is configurable my changing the $config['time_to_update'] line in your system/config/config.php file.</p>
128
129<h2>Retrieving Session Data</h2>
130
131<p>Any piece of information from the session array is available using the following function:</p>
132
133<code>$this->session->userdata('<samp>item</samp>');</code>
134
135<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
136will do this:</p>
137
138<code>$session_id = $this->session->userdata('<samp>session_id</samp>');</code>
139
140<p><strong>Note:</strong> The function returns FALSE (boolean) if the item you are trying to access does not exist.</p>
141
142
143<h2>Adding Custom Session Data</h2>
144
145<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.
146Why would you want to do this? Here's one example:</p>
147
148<p>Let's say a particular user logs into your site. Once authenticated,
149you could add their username and email address to the session cookie, making that data globally available to you without
150having to run a database query when you need it.</p>
151
152<p>To add your data to the session array involves passing an array containing your new data to this function:</p>
153
154<code>$this->session->set_userdata(<samp>$array</samp>);</code>
155
156<p>Where <samp>$array</samp> is an associative array containing your new data. Here's an example:</p>
157
158
159<p><code>$newdata = array(<br />
160 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'username'&nbsp; => 'johndoe',<br />
161 &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 />
162 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'logged_in' => TRUE<br />
163 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;);<br />
164 <br />
165 $this->session->set_userdata(<samp>$newdata</samp>);</code></p>
166<p>If you want to add userdata one value at a time, set_userdata() also supports this syntax. </p>
167<p><code>$this-&gt;session-&gt;set_userdata('some_name', 'some_value');</code></p>
168<p class="important"><strong>Note:</strong> Cookies can only hold 4KB of data, so be careful not to exceed the capacity. The
169encryption process in particular produces a longer data string than the original so keep careful track of how much data you are storing.</p>
170
171<h2>Removing Session Data</h2>
172<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>
173<p><code>$this-&gt;session-&gt;unset_userdata('some_name');</code></p>
Derek Jones4f953532007-09-10 16:37:12 +0000174<p>This function can also be passed an associative array of items to unset.</p>
175<p><code>$array_items = array('username' => '', 'email' => '');<br />
Derek Allard309d63f2007-08-17 11:49:29 +0000176<br />
Derek Jones4f953532007-09-10 16:37:12 +0000177$this-&gt;session-&gt;unset_userdata(<samp>$array_items</samp>);</code></p>
Derek Allard309d63f2007-08-17 11:49:29 +0000178<h2>Flashdata</h2>
Derek Allard2db431b2008-01-22 07:45:30 +0000179<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>
Derek Allard309d63f2007-08-17 11:49:29 +0000180<p>Note: Flash variables are prefaced with &quot;flash_&quot; so avoid this prefix in your own session names.</p>
181<p>To add flashdata:</p>
182<p><code>$this-&gt;session-&gt;set_flashdata('item', 'value');</code></p>
183<p>You can also pass an array to set_flashdata(), in the same manner as set_userdata(). </p>
184<p>To read a flashdata variable:</p>
185<p><code>$this-&gt;session-&gt;flashdata('item');</code></p>
186<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>
187<p><code>$this-&gt;session-&gt;keep_flashdata('item');</code></p>
188<h2>Saving Session Data to a Database</h2>
189<p>While the session data array stored in the user's cookie contains a Session ID,
190unless you store session data in a database there is no way to validate it. For some applications that require little or no
191security, session ID validation may not be needed, but if your application requires security, validation is mandatory.</p>
192
193<p>When session data is available in a database, every time a valid session is found in the user's cookie, a database
194query is performed to match it. If the session ID does not match, the session is destroyed. Session IDs can never
195be updated, they can only be generated when a new session is created.</p>
196
197<p>In order to store sessions, you must first create a database table for this purpose. Here is the basic
198prototype (for MySQL) required by the session class:</p>
199
200<textarea class="textarea" style="width:100%" cols="50" rows="8">
201CREATE TABLE IF NOT EXISTS `ci_sessions` (
202session_id varchar(40) DEFAULT '0' NOT NULL,
203ip_address varchar(16) DEFAULT '0' NOT NULL,
204user_agent varchar(50) NOT NULL,
205last_activity int(10) unsigned DEFAULT 0 NOT NULL,
206PRIMARY KEY (session_id)
207);</textarea>
208
209<p><strong>Note:</strong> By default the table is called <dfn>ci_sessions</dfn>, but you can name it anything you want
210as long as you update the <kbd>application/config/config.php</kbd> file so that it contains the name you have chosen.
211Once you have created your database table you can enable the database option in your config.php file as follows:</p>
212
213<code>$config['sess_use_database'] = TRUE;</code>
214
215<p>Once enabled, the Session class will store session data in the DB.</p>
216
217<p>Make sure you've specified the table name in your config file as well:</p>
218
219<code>$config['sess_table_name'] = 'ci_sessions";</code>
220
221<p class="important"><strong>Note:</strong> The Session class has built-in garbage collection which clears out expired sessions so you
222do not need to write your own routine to do it.</p>
223
224
225<h2>Destroying a Session </h2>
226<p>To clear the current session: </p>
227<code>$this-&gt;session-&gt;sess_destroy();</code>
228<h2>Session Preferences</h2>
229<p>You'll find the following Session related preferences in your <kbd>application/config/config.php</kbd> file:</p>
230
231
232<table cellpadding="0" cellspacing="1" border="0" style="width:100%" class="tableborder">
233<tr>
Derek Allard5b0a8812008-01-21 14:26:33 +0000234 <th>Preference</th>
235 <th>Default</th>
236 <th>Options</th>
237 <th>Description</th>
238</tr>
239<tr>
240 <td class="td"><strong>sess_cookie_name</strong></td>
241 <td class="td">ci_session</td>
242 <td class="td">None</td>
243 <td class="td">The name you world the session cookie saved as.</td>
244</tr>
245<tr>
246 <td class="td"><strong>sess_expiration</strong></td>
247 <td class="td">7200</td>
248 <td class="td">None</td>
249 <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>
250</tr>
251<tr>
252 <td class="td"><strong>sess_encrypt_cookie</strong></td>
253 <td class="td">FALSE</td>
254 <td class="td">TRUE/FALSE (boolean)</td>
255 <td class="td">Whether to encrypt the session data.</td>
256</tr>
257<tr>
258 <td class="td"><strong>sess_use_database</strong></td>
259 <td class="td">FALSE</td>
260 <td class="td">TRUE/FALSE (boolean)</td>
261 <td class="td">Whether to save the session data to a database. You must create the table before enabling this option.</td>
262</tr>
263<tr>
264 <td class="td"><strong>sess_table_name</strong></td>
265 <td class="td">ci_sessions</td>
266 <td class="td">Any valid SQL table name</td>
267 <td class="td">The name of the session database table.</td>
268</tr>
269<tr>
270 <td class="td"><strong>sess_time_to_update</strong></td>
271 <td class="td">300</td>
272 <td class="td">Time in milliseconds</td>
273 <td class="td">This options controls how often the session class will regenerate itself and create a new session id.</td>
274</tr>
275<tr>
276 <td class="td"><strong>sess_match_ip</strong></td>
277 <td class="td">FALSE</td>
278 <td class="td">TRUE/FALSE (boolean)</td>
279 <td class="td">Whether to match the user's IP address when reading the session data. Note that some ISPs dynamically
280 changes the IP, so if you want a non-expiring session you will likely set this to FALSE.</td>
281</tr>
282<tr>
283 <td class="td"><strong>sess_match_useragent</strong></td>
284 <td class="td">TRUE</td>
285 <td class="td">TRUE/FALSE (boolean)</td>
286 <td class="td">Whether to match the User Agent when reading the session data.</td>
Derek Allard309d63f2007-08-17 11:49:29 +0000287</tr>
288</table>
289
290
291</div>
292<!-- END CONTENT -->
293
294
295<div id="footer">
296<p>
297Previous Topic:&nbsp;&nbsp;<a href="pagination.html">Pagination Class</a>
298&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
299<a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
300<a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp;
301Next Topic:&nbsp;&nbsp;<a href="trackback.html">Trackback Class</a>
302</p>
Derek Jones7a9193a2008-01-21 18:39:20 +0000303<p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2007 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">Ellislab, Inc.</a></p>
Derek Allard309d63f2007-08-17 11:49:29 +0000304</div>
305
306</body>
adminb0dd10f2006-08-25 17:25:49 +0000307</html>