Using native PHP sessions with CodeIgniter

By Steve Claridge on 2014-03-15.

This post explains how to use native PHP sessions ( the $_SESSION["] global array ) with CodeIgniter 2.1.0 in place of CodeIgniter's default session storage.

CodeIgniter doesn't use standard PHP sessions, instead it saves session-data directly in a browser cookie, which limits the amount of data you can save to 4k. Even though it is good practice not to store a lot of data in session it's unlikely that 4k is going to be enough for any reasonably complicated website. I find it kinda odd that the CI developers didn't at least give us a configuration option to switch to using standard PHP sessions. Luckily for us it is easy to add a library to save the day.

Creating the Nativesession library

A CodeIgniter library is simply a class that is loaded by the framework and made available for you to use in your Controller classes. It's simple but a really nice way to include your own code without having to add include statements and instantiation code into each controller that you create. We are going to create a new library that starts a native PHP session and allows us to store and retrieve things from it:

Create the native session class

Inside your CodeIgniter project you have an application/libraries folder, create a new file called Nativesession.php in there. Put the following code into Nativesession.php:

if ( ! defined('BASEPATH') )
    exit( 'No direct script access allowed' ); class Nativesession
{
    public function __construct()
    {
        session_start();
    }     public function set( $key, $value )
    {
        $_SESSION[$key] = $value;
    }     public function get( $key )
    {
        return isset( $_SESSION[$key] ) ? $_SESSION[$key] : null;
    }     public function regenerateId( $delOld = false )
    {
        session_regenerate_id( $delOld );
    }     public function delete( $key )
    {
        unset( $_SESSION[$key] );
    }
}

If you've used PHP sessions before then that code should be pretty self-explanatory, if not, check the PHP site for more info.

Using your new library in a controller

You use your new library in the same way as you do any other CI library:

class Login extends CI_Controller 
{
    public function index()
    {
        //load our Nativesession library
        $this->load->library( 'nativesession' );		         //Read the username from session
        $username = $this->nativesession->get( 'username' );         //Update shopping cart session data
        $this->nativesession->set( 'cart', $cart );
    }
}

You can now use your new Nativesession library in place of the CI-supplied session library.