To create a login, registration, and logout authentication system in a CodeIgniter application you must use the build Session() method to store logged in user data in session.
Let’s start to create login, registration and logout authentication system:
Step 1: Set Up CodeIgniter 4
Run the following command to install codeIgniter 4 application:
composer create-project codeigniter4/appstarter ci4-auth
cd ci4-auth
Step 2: Create Table in DB
Run the following sql query to create table into your selected database:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 3: Set Up Database
Edit app/Config/Database.php
file, and set up database details:
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'ci4_auth',
'DBDriver' => 'MySQLi',
'charset' => 'utf8',
'DBDebug' => (ENVIRONMENT !== 'production'),
'cacheOn' => false,
'cachedir' => '',
'charSet' => 'utf8',
'DBPrefix' => '',
'returnType' => 'array',
'protectIdentifiers' => true,
'foreignKeys' => false,
];
Step 4: Create Model
Create a UserModel.php
file in the App/models
directory to interact with the database:
// app/Models/UserModel.php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $allowedFields = ['username', 'email', 'password'];
protected $useTimestamps = true;
}
Step 5: Create Auth Controller
Go to the app/controllers
directory and create the auth.php
controller file that handles the login, registration, and logout logic.
// app/Controllers/Auth.php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\Controller;
class Auth extends Controller
{
public function register()
{
helper(['form']);
// Check if user is already logged in
if (session()->get('user_id')) {
return redirect()->to('/dashboard');
}
$data = [];
if ($this->request->getMethod() === 'post') {
$rules = [
'username' => 'required|min_length[3]|max_length[50]',
'email' => 'required|valid_email',
'password' => 'required|min_length[6]',
];
if (!$this->validate($rules)) {
$data['validation'] = $this->validator;
} else {
$model = new UserModel();
$model->save([
'username' => $this->request->getPost('username'),
'email' => $this->request->getPost('email'),
'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
]);
return redirect()->to('/auth/login');
}
}
return view('auth/register', $data);
}
public function login()
{
helper(['form']);
// Check if user is already logged in
if (session()->get('user_id')) {
return redirect()->to('/dashboard');
}
$data = [];
if ($this->request->getMethod() === 'post') {
$model = new UserModel();
$user = $model->where('email', $this->request->getPost('email'))->first();
if ($user && password_verify($this->request->getPost('password'), $user['password'])) {
session()->set('user_id', $user['id']);
return redirect()->to('/dashboard');
} else {
$data['error'] = 'Invalid email or password.';
}
}
return view('auth/login', $data);
}
public function logout()
{
session()->destroy();
return redirect()->to('/auth/login');
}
}
And create dashboard.php
controller file to handle user profile:
// app/Controllers/Dashboard.php
namespace App\Controllers;
use CodeIgniter\Controller;
class Dashboard extends Controller
{
public function index()
{
// Check if user is logged in
if (!session()->get('user_id')) {
return redirect()->to('/auth/login');
}
return view('dashboard');
}
}
Step 6: Create Views
Create login.php
, registration.php
, and dashboard.php
views in the app/views
directory to show the login page, registration page, and dashboard page to the user:
In Login.php file:
<!-- app/Views/auth/login.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Form in CodeIgniter 4 - itcodStuff.com</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5">Login</h1>
<?php if (isset($error)) : ?>
<div class="alert alert-danger">
<?= $error ?>
</div>
<?php endif; ?>
<form action="/auth/login" method="post">
<?= csrf_field() ?>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" value="<?= old('email') ?>">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</body>
</html>
In registration.php file:
<!-- app/Views/auth/register.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Registeration in CodeIgniter 4 - ItcodStuff.com</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5">Register</h1>
<?php if (isset($validation)) : ?>
<div class="alert alert-danger">
<?= $validation->listErrors() ?>
</div>
<?php endif; ?>
<form action="/auth/register" method="post">
<?= csrf_field() ?>
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" value="<?= old('username') ?>">
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" value="<?= old('email') ?>">
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password">
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</body>
</html>
In Dashboard.php file:
<!-- app/Views/dashboard.php -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login and Registration - Dashboard Page - itcodstuff.com</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1 class="mt-5">Welcome to the Dashboard</h1>
<a href="/auth/logout" class="btn btn-danger">Logout</a>
</div>
</body>
</html>
Step 7: Define Routes
Edit app/Config/Routes.php
file, and define authentication routes in it:
$routes->group('', function($routes) {
$routes->match(['get', 'post'], 'auth/register', 'Auth::register');
$routes->match(['get', 'post'], 'auth/login', 'Auth::login');
$routes->get('auth/logout', 'Auth::logout');
$routes->get('/dashboard', 'Dashboard::index');
});
Step 8: Test Application
Run the following command to start application server:
php spark serve
Type the url http://localhost:8080/auth/register on browser to test the application.