agyanadda@gmail.com

CodeIgniter 4 Login and Registration

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

There are two ways to add login to a CodeIgniter 4 site.

Option 1: CodeIgniter Shield (recommended for real projects)

Shield is the official authentication library. It gives you login, registration, remember-me, groups and permissions, and API tokens.

  1. composer require codeigniter4/shield
  2. php spark shield:setup
  3. Protect routes with the session filter

Option 2: Build your own (great for learning)

  1. Register — validate, then save the password with password_hash($password, PASSWORD_DEFAULT)
  2. Login — find the user by email and check with password_verify($password, $user['password'])
  3. On success: session()->regenerate(), then store user_id and role in the session
  4. Protect pages with an auth filter that checks session('user_id')
  5. Logout — session()->destroy() and redirect

Security rules

  • Never store plain-text passwords, and never use md5() or sha1() for passwords
  • Show the same message for a wrong email or wrong password ("Invalid email or password")
  • Use HTTPS on the live site
  • Limit login attempts (the throttler service helps)

Example

Example — Login and logout PHP
<?php
namespace App\Controllers;

class Auth extends BaseController
{
    public function login()
    {
        if (! $this->validate(['email' => 'required|valid_email', 'password' => 'required'])) {
            return redirect()->back()->withInput();
        }

        $user = model('UserModel')->where('email', $this->request->getPost('email'))->first();

        if (! $user || ! password_verify($this->request->getPost('password'), $user['password'])) {
            return redirect()->back()->withInput()->with('error', 'Invalid email or password.');
        }

        session()->regenerate();
        session()->set(['user_id' => $user['id'], 'name' => $user['name'], 'role' => $user['role']]);

        return redirect()->to('dashboard');
    }

    public function logout()
    {
        session()->destroy();

        return redirect()->to('login')->with('success', 'You have logged out.');
    }
}

Correct details log the user in and open /dashboard. Wrong details return to the form with "Invalid email or password." Logout ends the session.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function checks a password against its stored hash?

Exercise 2 True / False

md5() is a safe way to store passwords.

Exercise 3 Fill in the Blank

CodeIgniter's official authentication library is called ___.

Frequently Asked Questions

Build your own once to understand how it works. For real projects, use Shield: it already handles remember-me, password resets, throttling, groups and permissions, and it is maintained by the CodeIgniter team.