How to use native PHP session in codeigniter

In this tutorial I will explain how to use native PHP session in codeigniter. CodeIgniter doesn’t use standard PHP sessions, instead it saves session-data directly in a browser cookie. You can add your own library to use native session in codeigniter.

A CodeIgniter library is simply a class that is loaded by the framework and made available for you to use in your Controller classes.  We are going to create a new library that starts a native PHP session and allows us to store and retrieve things from it.

Go to application/libraries

Create a file name Native_session.php

<?php
 
if ( ! defined('BASEPATH') )
    exit( 'No direct script access allowed' );
 
class Native_session
{
    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 newID( $delOld = false )
    {
        session_newID_id( $delOld );
    }
 
    public function delete( $key )
    {
        unset( $_SESSION[$key] );
    }
}
 
?>

 

Using your new library in a controller.

 

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

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

Hope this article how to use native PHP session in codeigniter will help you.

For more on codeigniter supplied session library read this tutorial:Session handling in Codeigniter