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.
composer require codeigniter4/shieldphp spark shield:setup- Protect routes with the
sessionfilter
Option 2: Build your own (great for learning)
- Register — validate, then save the password with
password_hash($password, PASSWORD_DEFAULT) - Login — find the user by email and check with
password_verify($password, $user['password']) - On success:
session()->regenerate(), then storeuser_idandrolein the session - Protect pages with an auth filter that checks
session('user_id') - Logout —
session()->destroy()and redirect
Security rules
- Never store plain-text passwords, and never use
md5()orsha1()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
throttlerservice 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.