How to Set Session in CodeIgniter with Example

โšก Smart Summary

CodeIgniter Session Management stores user data across stateless HTTP requests, letting an application remember a logged-in user, cart items, or one-time flash messages. This example builds flash messaging and a simulated login using the CodeIgniter session library.

  • ๐ŸŒ Why Sessions: HTTP is stateless, so sessions preserve user data such as login state across separate page requests on the server.
  • ๐Ÿช Cookies vs Sessions: Cookies store small data on the user’s computer, while sessions store larger data on the server and are safer for sensitive values.
  • ๐Ÿ’จ Flash Data: set_flashdata() stores a message available only on the next request, ideal for one-time feedback after a redirect.
  • ๐Ÿ”‘ User Data: set_userdata() persists values like username and logged_in for the full session, and unset_userdata() clears them on logout.
  • ๐Ÿ›ก๏ธ Access Control: A reusable check_auth() method redirects visitors to the login page whenever the logged_in session key is missing.
  • ๐Ÿงช Working Example: The tutorial wires routes, a controller, and Bulma-styled views to demonstrate both flash and persistent session flows.
  • ๐Ÿค– AI Assist: AI tools can scaffold session controllers, generate route maps, and flag insecure session handling before deployment.

CodeIgniter Session Management

CodeIgniter Session Management

If you have developed desktop applications before, then you probably know that you can define a global variable, assign a value to it, and use it throughout the life cycle of the application. Opening and closing more than one form, each request will have access to the global variable.

In other words, the state of the application is maintained. That is to say, if when you logged in you set the company name to a global variable, then even after you close the login form that state of the company name is preserved.

HTTP works a bit differently from the scenario that we have just described. It is stateless. That is to say, whatever you do in one request does not persist in the next request.

To work around this problem, we have two (2) solutions in PHP. We can either work with cookies, which are small files placed on the user’s computer, or work with sessions, which are similar to cookies but are instead stored on the server and have a bigger capacity than cookies.

When to use sessions?

Sessions are usually useful when you want to know the user’s activities from page to page. For example, let us say you have a protected area on the website. The users do not need to login on each page. You can let the user login once and store their details in a session variable, then reuse the same data on further requests. Other use cases include when working on a shopping system and the user has to add items to the shopping cart.

Alternatively, CodeIgniter also uses sessions to make data available only once on the next request. This is useful when you have edited and updated a database record, and you want to return some feedback to the user when they are redirected to another page.

Sending Flash Messages to other pages with CI Sessions

In this section, you will learn about sending flash messages to other pages using the session library in CodeIgniter.

Create a new file SessionController in

application/controllers/SessionController.php

Add the following code

<?php defined('BASEPATH') OR exit('No direct script access allowed');

class SessionController extends CI_Controller {

public function __construct() {
parent:: __construct();

$this->load->helper('url');
$this->load->library('session');
}

public function index() {

$this->load->view('sessions/index');
}

public function flash_message(){
$this->session->set_flashdata('msg', 'Welcome to CodeIgniter Flash Messages');
redirect(base_url('flash_index'));
}
}

HERE,

  • class SessionController extends CI_Controller {…} defines the SessionController class and extends the parent controller class.
  • public function __construct() {…} defines the constructor method that initializes the parent class, and loads the url helper and session library.
  • public function index() {…} defines the session index method that loads the session index view.
  • public function flash_message(){…} defines the flash message method which sets the flash data then redirects to the flash_index route

Let us now create the view that will display the value of the session data.

Create a new directory sessions in application/views

Create a new file index.php in application/views/sessions

Add the following code

<html>
<head>
<title>Code Igniter Flash Session</title>
</head>
<body>
<p>The session value of msg is <b> <?= $this->session->userdata('msg');?> </b></p>
</body>
</html>

HERE,

<?= $this->session->userdata(‘msg’);?> retrieves the value of the session data with the key of msg and displays it in the browser.

Let us now create the routes for our session flash method

Open application/config/routes.php

Add the following lines

$route['flash_index'] = 'sessioncontroller';
$route['flash_message'] = 'sessioncontroller/flash_message';

Let us now start the built-in server for PHP and test our flash messages

Open the terminal

Run the following command

cd C:\Sites\ci-app
php -S localhost:3000

HERE,

The above command browses to the application code directory and starts the built-in server on port 3000.

Note: the application path has to match the path where you downloaded CodeIgniter, and you can use any port number that is free on your computer. It is not necessary to use port 3000.

Load the following URL in your web browser: http://localhost:3000/flash_message

You will be redirected to the following URL, and you will get the following results: http://localhost:3000/flash_index

Sending Flash Messages to other pages

Click on the refresh button of your web browser or press F5

You will now get the following results

Sending Flash Messages to other pages

Storing User Data in CI Sessions

Let us now look at a slightly more advanced example. To make it simple, we will simulate user authentication and not do the actual implementation of verifying the user record in the database and the submitted password.

Let us start with the routes

Open routes.php located in application/config

Add the following routes

$route['login'] = 'sessioncontroller/login';
$route['authenticate'] = 'sessioncontroller/authenticate';
$route['settings'] = 'sessioncontroller/settings';
$route['dashboard'] = 'sessioncontroller/dashboard';
$route['logout'] = 'sessioncontroller/logout';

HERE,

  • $route[‘login’] = ‘sessioncontroller/login’; defines the route that displays the login form
  • $route[‘authenticate’] = ‘sessioncontroller/authenticate’; defines the route that simulates successful user login and sets the session login data.
  • $route[‘settings’] = ‘sessioncontroller/settings’; defines a protected page that should only be accessible to logged in users
  • $route[‘dashboard’] = ‘sessioncontroller/dashboard’; defines a protected page that should only be accessible to logged in users.
  • $route[‘logout’] = ‘sessioncontroller/logout’; logs out the user by destroying the session data

Let us now update the SessionController

Open application/controllers/SessionController.php

Add the following methods

public function check_auth($page) {
if (!$this->session->userdata('logged_in')) {
$this->session->set_flashdata('msg', "You need to be logged in to access the $page page.");
redirect('login');
}
}

public function login() {
$this->load->view('sessions/login');
}

public function authenticate() {
$this->session->set_userdata('username', 'John Doe');
$this->session->set_userdata('logged_in', TRUE);
redirect(base_url('dashboard'));
}

public function dashboard() {
$this->check_auth('dashboard');
$this->load->view('sessions/dashboard');
}

public function settings() {
$this->check_auth('settings');
$this->load->view('sessions/settings');
}

public function logout() {
$this->session->unset_userdata('username');
$this->session->unset_userdata('logged_in');
redirect(base_url('login'));
}

HERE,

  • public function check_auth($page) {…} defines the method that checks if the user is logged in, then allows access to the page. If a user is not logged in, then the user is redirected to the login page with a flash message.
  • public function login() {…} loads the login view located in the sessions directory.
  • public function authenticate() {…} sets the session user data for the keys logged_in and username. NOTE: We are not verifying any login details against the database. We are simply assuming the submitted details are ok and set the session data.
  • public function dashboard() {…} loads the dashboard page after calling $this->check_auth(‘dashboard’); which verifies that the logged_in session key is set.
  • public function settings() {…} loads the settings page, which is also protected
  • public function logout() {…} destroys the session data and signs out the user. The method also redirects to the login page

CodeIgniter Session Views

Create the following views in application/views/sessions

  • dashboard.php
  • login.php
  • settings.php

Add the following code to dashboard.php

<!DOCTYPE html>
<html>
<head>
<title>Dashboard</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https:0
</head>
<body>
<div class="container">
<div class="column">
<nav class="navbar" role="navigation" aria-label="main navigation">
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
<a href="<?= site_url('dashboard')?>" class="navbar-item is-active">Dashboard</a>
<a href="<?= site_url('settings')?>" class="navbar-item">Settings</a>
</div>
 
<div class="navbar-end">
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link"><?=$this->session->userdata(3);?></a>
 
<div class="navbar-dropdown">
<a class="navbar-item">My Profile</a>
<hr class="navbar-divider">
<a class="navbar-item">Sign out</a>
</div>
</div>
</div>
</div>
</nav>
<h3>Welcome Page</h3>
</div>
</div>
</body>
</html>

HERE,

<?=$this->session->userdata(‘username’);?> displays the user name which we set in the authentication method

Add the following code to login.php

<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https:0
</head>
<body>
<div class="container">
<div class="column">
<p><?=$this->session->userdata(1);?></p>
<form method="post" action="<?= site_url('authenticate')?>">
<div class="field">
<label class="label">Username</label>
<div class="control">
<input class="input" type="text" placeholder="Text input">
</div>
</div>
<div class="field">
<label class="label">Password</label>
<div class="control">
<input class="input" type="password" placeholder="Text input">
</div>
</div>
<div class="field is-grouped">
<div class="control">
<button class="button is-success">Login</button>
</div>
</div>
</form>
</div>
</div>
</body>
</html>

HERE,

The login form submits to the authenticate route.

Add the following code to settings.php

<!DOCTYPE html>
<html>
<head>
<title>Settings</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https:0
</head>
<body>
<div class="container">
<div class="column">
<nav class="navbar" role="navigation" aria-label="main navigation">
<div id="navbarBasicExample" class="navbar-menu">
<div class="navbar-start">
<a href="<?= site_url('dashboard')?>" class="navbar-item">Dashboard</a>
<a href="<?= site_url('settings')?>" class="navbar-item">Settings</a>
</div>
 
<div class="navbar-end">
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link">Jim Jones</a>
 
<div class="navbar-dropdown">
<a href="#" class="navbar-item">My Profile</a>
<hr class="navbar-divider">
<a href="<?= site_url('logout')?>" class="navbar-item">Sign out</a>
</div>
</div>
</div>
</div>
</nav>
<h3>Settings Page</h3>
</div>
</div>
</body>
</html>

That’s it for our views. Let us now test our application.

In this tutorial, we are using the built-in PHP web server, but you can use any web server that supports PHP.

Open the terminal

Run the following command

cd C:\Sites\ci-app
php -S localhost:3000

HERE,

The above command browses to the application code directory and starts the built-in server on port 3000.

Note: the application path has to match the path where you downloaded CodeIgniter, and you can use any port number that is free on your computer. It is not necessary to use port 3000.

Open the following URL in your web browser: http://localhost:3000/dashboard

You will be redirected to the following page

CodeIgniter Session Views

Click on the Login button

You will see the following results

CodeIgniter Session Views

After we log in, we are now able to see the session data.

FAQs

Userdata persists for the entire session until you unset it or the session expires. Flashdata is a temporary value that survives only the very next request and is then removed automatically, which suits one-time messages.

Tempdata is session data with a set expiry time. You call mark_as_temp() or set_tempdata() with a lifetime in seconds, after which CodeIgniter removes the value automatically, even if the session is still active.

By default CodeIgniter stores sessions using files on the server. You can switch the driver to database, Redis, or Memcached in the config file when you need shared storage across multiple servers.

Yes. AI can review your session config for weak settings, recommend regenerating the session ID after login, enabling cookie encryption, and using HTTPS-only cookies to reduce session hijacking risks.

Yes. From a short description, AI can produce the routes, a session controller, and the protected views. Always add real database verification and password hashing, since AI scaffolds often use simulated checks.

Summarize this post with: