Skip to main content
Session Management

Session Management

Sessions keep data between requests, such as the signed-in user or a shopping cart. CodeIgniter stores the data on the server and sends only a cookie identifier to the browser.

Read and write

$session = session();

$session->set('user_id', 42);
$session->set(['role' => 'editor', 'last_seen' => time()]);

$userId = $session->get('user_id');
$role   = $session->get('role');

Remove data

$session->remove('last_seen');
$session->remove(['role', 'user_id']);
$session->destroy(); // full sign-out

Regenerate the identifier

Call regenerate() after a successful sign-in to prevent session fixation. On sign-out, destroy the session and expire the cookie.

$session->regenerate();
$session->destroy();

Configuration and safety

  • Choose a driver such as files, database, or Redis depending on your hosting.
  • Set the cookie to HttpOnly and Secure when the site runs on HTTPS.
  • Use SameSite=Lax or Strict unless a cross-site flow needs otherwise.
  • Do not store sensitive personal data in the session; store an identifier and look up the record.
  • Keep admin session lifetimes short and expire idle sessions.

Flashdata and tempdata are specialised session features covered in the next two topics.