Sessions and Cookies

📘 CodeIgniter 👁 34 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Sessions and Cookies in CodeIgniter (CodeIgniter 4)

Sessions and Cookies are used to store user-related data across requests. CodeIgniter provides a secure and easy-to-use API for both.


1. Sessions

What Is a Session?

  • Stores data on the server

  • Identified by a session ID stored in a cookie

  • Commonly used for login/authentication


Session Configuration

File:

app/Config/App.php

Key settings:

public $sessionDriver = 'CodeIgniter\Session\Handlers\FileHandler'; public $sessionSavePath = WRITEPATH . 'session';

Starting a Session

Sessions are auto-started in CodeIgniter 4.

Access session:

$session = session();

Setting Session Data

$session->set('username', 'john');

Multiple values:

$session->set([ 'id' => 1, 'role' => 'admin' ]);

Getting Session Data

$username = $session->get('username');

Check existence:

$session->has('username');

Removing Session Data

$session->remove('username');

Destroy session:

$session->destroy();

Flashdata (Temporary Session Data)

Used for one-time messages (success/error).

$session->setFlashdata('success', 'Login successful');

Retrieve in view:

<?= session()->getFlashdata('success') ?>

Example: Login Session

$session->set([ 'user_id' => $user['id'], 'logged_in' => true ]);

Check login:

if (! session()->get('logged_in')) { return redirect()->to('/login'); }

2. Cookies

What Is a Cookie?

  • Stored on the client (browser)

  • Has size and security limitations

  • Used for preferences, remember-me, etc.


Setting a Cookie

helper('cookie'); set_cookie('theme', 'dark', 3600); // 1 hour

Getting a Cookie

get_cookie('theme');

Deleting a Cookie

delete_cookie('theme');

Secure Cookies

set_cookie([ 'name' => 'token', 'value' => 'abc123', 'expire' => 3600, 'secure' => true, 'httponly' => true ]);

3. Sessions vs Cookies

FeatureSessionsCookies
StorageServerBrowser
SecurityHighLower
SizeLargeSmall
Use CaseLogin, authPreferences

4. Best Practices

✅ Use sessions for sensitive data
✅ Use flashdata for messages
✅ Enable httponly & secure cookies
❌ Never store passwords in cookies


5. Common Use Cases

  • User authentication

  • Shopping cart

  • Language preference

  • Theme settings


Summary

  • Sessions store server-side user data

  • Cookies store client-side data

  • CodeIgniter provides secure APIs for both

  • Essential for authentication & UX


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes