agyanadda@gmail.com

CodeIgniter 4 Sessions and Flash Data

Forms, Sessions and Security 1 min read Updated Dec 3, 2026 Topic 19 of 30

A session stores data for one visitor across page loads — such as the logged-in user's id or a shopping cart.

Getting the session

Use the session() helper. It starts the session automatically.

Basic methods

  • session()->set('user_id', 5) or set several with an array
  • session('user_id') or session()->get('user_id')
  • session()->has('user_id')
  • session()->remove('cart')
  • session()->destroy() — end the whole session (logout)

Flash data

Flash data lives for one request — perfect for messages after a redirect:

  • session()->setFlashdata('success', 'Saved!') (or redirect()->with('success', 'Saved!'))
  • In the view: session()->getFlashdata('success')

Security

Call session()->regenerate() right after login. It gives a new session ID and prevents session fixation attacks.

Where sessions are stored

Settings are in app/Config/Session.php. The default FileHandler stores sessions in writable/session. You can switch to the database or Redis handler for multi-server sites.

Example

Example — Simple cart in the session PHP
<?php
public function addToCart(int $productId)
{
    $cart = session('cart') ?? [];
    $cart[$productId] = ($cart[$productId] ?? 0) + 1;

    session()->set('cart', $cart);

    return redirect()->back()->with('success', 'Added to cart');
}

public function cartCount(): int
{
    return array_sum(session('cart') ?? []);
}

// View (layout)
// <?php if (session()->getFlashdata('success')): ?>
//   <div class="alert alert-success"><?= esc(session()->getFlashdata('success')) ?></div>
// <?php endif ?>

Each click adds one of the product to the cart stored in the session. The "Added to cart" message shows once and disappears on the next page load.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method should you call right after a user logs in?

Exercise 2 True / False

Flash data is available only for the next request.

Exercise 3 Fill in the Blank

End the whole session on logout with session()->___()

Frequently Asked Questions

With the default FileHandler they are in writable/session. Errors usually mean that folder is not writable by the web server. Fix the folder permissions, or switch to the database handler.