-
Notifications
You must be signed in to change notification settings - Fork 7.6k
DB Session
Code Igniter bundles a session class, working with cookies. Unfortunately, this class stores session data directly inside the cookie, thus allowing the client to see and edit those data. Here is a replacement class that stores data in the database. (note: the original Code Igniter can use a database, but only for validation purposes. The actual data is stored in the cookie itself)
[h3]1/ Using the class[/h3]
This class works with the new CodeIgniter v1.4 ! (and 1.5)
The usage is the same as the bundled Code Igniter session class. So you use it like :
[code]$this->db_session->set_userdata('info', 'some thing interesting');[/code]
and get back data like :
[code]$foo = $this->db_session->userdata('info');[/code]
This class supports so called "flashdata" variables, which are variables that persist only for the next request. More information at Native_session.
[h3]2/ Configuration[/h3]
This class uses the same configuration directives than the original session class. So don't forget to set inside your 'config.php' :
[code]$config['sess_cookie_name'] = 'mysite'; $config['sess_expiration'] = 7200; $config['sess_use_database'] = TRUE; $config['sess_table_name'] = 'ci_sessions'; $config['sess_match_ip'] = TRUE; $config['sess_match_useragent'] = FALSE; $config['cookie_prefix'] = ""; $config['cookie_domain'] = ""; $config['cookie_path'] = "/";[/code]
[h3]3/ Database[/h3]
Here is the table schema needed by the new session class :
[code]CREATE TABLE IF NOT EXISTS ci_sessions
(
session_id varchar(40) DEFAULT '0' NOT NULL,
ip_address varchar(16) DEFAULT '0' NOT NULL,
user_agent varchar(50) NOT NULL,
last_activity int(10) unsigned DEFAULT 0 NOT NULL,
session_data text default '' not null,
PRIMARY KEY (session_id)
);[/code]
[h3]4/ Installing the package[/h3]
Just get the zip File:db_sessions.zip .
Move the file [b]DB_Session.php[/b] in your [b]application/libraries[/b] directory, and (for CI < 1.5) the file [b]init_db_session.php[/b] inside your [b]application/init[/b] directory. Then use the autoload feature of Code Igniter : open your "autoload.php" configuration file and add "db_session" in the core autoload array :
For ci < 1.5: [code]$autoload['core'] = array('database','db_session');[/code]
For ci > 1.5 [code]$autoload['libraries'] = array('database', 'db_session');[/code]
For CI 1.5 the init_db_session.php files is not needed. Simply rename the DB_Session.php file to Session.php and change the class name constructor function to Session. Then of course autoload or load session.
[h3]5/ Inside working[/h3]
Using this class, the cookie only stores a unique session identifier. Everything else is matched from the database.