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