Step 8 (optional) – Using sessions with database in CodeIgniter

(created at: January 23, 2014; last update: April 1, 2015)
By default, session data is saved as files on the server. Here is a video tutorial of mine regarding how to use the file driver to store session data:

In this tutorial though we will learn about storing session data in the database. To do this we first need to go to the config.php file and look for the line:

$config['sess_driver'] = 'files';

We should change this line to:

$config['sess_driver'] = 'database';

Also, after this line we should write another one that will tell the CodeIgniter framework what table it should use for storing the session data (make sure it doesn’t already exist):

$config['sess_save_path'] = 'ci_sessions';

To create a table we should first have a database. So let’s create it. I will name mine “ciapp” and set the collation to “utf8_general_ci”. Now let’s create the table:

For MySql we can simply paste this sql command:

CREATE TABLE IF NOT EXISTS `ci_sessions` (
        `id` varchar(40) NOT NULL,
        `ip_address` varchar(45) NOT NULL,
        `timestamp` int(10) unsigned DEFAULT 0 NOT NULL,
        `data` blob NOT NULL,
        PRIMARY KEY (id),
        KEY `ci_sessions_timestamp` (`timestamp`)
);

Now let’s set up the database.php that we have inside application/config/development directory (if you don’t have it there, you can simply move the one that is inside the config directory):

$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ciapp',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE, // make sure pconnect is set to false for sessions to work
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'autoinit' => TRUE,
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);

Now you go to the autoload.php, and add “session” to the drivers element:

$autoload['library'] = array('session');

If on visiting http://localhost you can’t see an error and by looking to the database you see at least one record (your visit), then you are ready to go. But do you need sessions across entire website? If you don’t, then it is a better idea not to “autoload” it.

4 comments

  1. Mercy mi-a fost de ajutor pt 3.0,
    Vezi ca ai omis sa treci ‘id’ in loc de ‘session_id’ pt primary key la create table in sql command.

    1. Multumesc pentru atentionare. Tutorialul a fost realizat inca inainte sa apara versiunea 3.0. Era inca in stadiul “dev” si s-ar putea ca acum sa fie unele scapari, chiar si la celelalte tutoriale. Daca mai reperezi astfel de erori, te rog sa imi spui. Multumesc.

  2. Just a note to the SQL Queries above. THe MYSQL SQL standards does not need single quotes for table name and field names. Hence the below can be used instead. 🙂
    ==========================================
    CREATE TABLE IF NOT EXISTS ci_sessions (
    id varchar(40) NOT NULL,
    ip_address varchar(45) NOT NULL,
    timestamp int(10) unsigned DEFAULT 0 NOT NULL,
    data blob NOT NULL,
    PRIMARY KEY (id),
    KEY ci_sessions_timestamp (timestamp)
    );
    =========================================

  3. Hi,

    Your tutorials have been really helpful and i appreciate the good work. Could you write a tutorial on how to build a reusable template using codeigniter? I have been trying without much success.

Leave a Reply

Your email address will not be published. Required fields are marked *

No spam? * Time limit is exhausted. Please reload CAPTCHA.