The authentication system in any application is the main security feature. If you don’t want to give the open-access of your application to the user then it will require to have a lock. Here the authentication will work as an access key for that lock. At the application level, the user will need to enter into the system before using it. There are some open-source packages are available which provide the auth system. But, in this post, I am not going to talk about those auth packages. I will implement the custom login and registration auth system with logout and session. I will show you the implementation of the Codeigniter 4 login and registration system from scratch. In the last post of Codeigniter 4, we have seen to send email using Gmail SMTP. So, let’s start by creating a new application.
Prerequisites
In order to create a new project set up in Codeigniter 4, you must have the below configuration.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
When you are ready, let’s create the application using the composer.
Create Project For Codeigniter 4 Login and Registration
Open the terminal for creating the Codeigniter login authentication system project. In the terminal simply enter the below command.
composer create-project codeigniter4/appstarter ci4-login
The above command will start creating a new project set up in Codeigniter 4.
Before moving the functionality implementation, you will require to configure the project environment.
How to Implement jQuery Datatable in CodeIgniter 4
Configure Project Environment in CodeIgniter 4
Initially, open the project in VS Code editor, and in the root of the project, you will see the env file. At the very first step, you need to rename it to .env. Now, open this file and search for the Environment configuration.
You have to change the environment to development from the production.
#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------
CI_ENVIRONMENT = development
Now, come to the database configuration. Firstly, create a database inside the MySQL database. Then configure it in the same file that is .env.
Configure Database in Codeigniter 4
In the .env file, you will see the database section. So, come to the database section, now, enter the database credentials as showing below.
database.default.hostname = localhost
database.default.database = ci4_form
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
That’s it for the configuration for this project. Now, we can focus on the Codeigniter login auth system. Before moving to the implementation, let’s understand what will do in this project.
We will create a user authentication system. So, the application will contain the Codeigniter login and signup module. Initially, there will be a user registration form. Then the login form for the authentication of the user. For creating Codeigniter login auth for the user, we won’t use any package as I already told you.
Here, we will be having the Codeigniter login form that will contain the inputs for validating the auth user.
Generate Fake Data in CodeIgniter 4 Using Seeder and Faker
Create Migration in Codeigniter 4
We are going to work on the User module. So, firstly, we will create a table. As we already know, Codeigniter 4 provides the migration functionality to create tables. You can manage the table schemas using migration.
Hence, inside the project, open the terminal and hit the below command.
php spark make:migration users --table
The above command will create a migration file inside the app/Database/Migration folder. Now, open the created migration file, and add some columns inside it as showing below.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Users extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'password' => [
'type' => 'VARCHAR',
'constraint' => '255'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('users');
}
public function down()
{
$this->forge->dropTable('users');
}
}
Here, we added some fields for the users table schema. Now, this table will need to migrate so that it can dump the schema inside the database.
Migrate Tables in Codeigniter 4
For migrating the table, hit the below command. It will dump the schema of the users table inside the database.
php spark migrate
It will dump the schemas of the migration inside the database.
Create a Model For CodeIgniter Login Sign Up Auth
For creating the model, we will use the spark command. The spark command will generate the model. So, hit the below command.
php spark make:model User
After creating the model, let’s navigate to the file and add the fillable data inside it. In the model, we need to specify the column name in the form of an array.
<?php
namespace App\Models;
use CodeIgniter\Model;
class User extends Model
{
protected $DBGroup = 'default';
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $protectFields = true;
protected $allowedFields = ['name', 'email', 'password'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
}
After configuring model, you are done with the table and fillable data. In the next step, you will need to create a controller for writing the functionality for the user authentication.
How to Remove index.php From URL in CodeIgniter 4
Create Controller For Codeigniter Login Auth
For creating the controller, you can create using the spark command. So, just switch back to the terminal and hit the below command.
php spark make:controller UserController
The above command will create the controller with the name UserController.php.
After creating the controller, let’s put the functionalities inside it for the user registration, login, logout with the session.
<?php
namespace App\Controllers;
use App\Controllers\BaseController;
use App\Models\User;
class UserController extends BaseController
{
private $user;
private $session;
/**
* constructor
*/
public function __construct()
{
helper(['form', 'url', 'session']);
$this->user = new User();
$this->session = session();
}
/**
* register
*/
public function register()
{
return view('register');
}
/**
* register
*/
public function create()
{
$inputs = $this->validate([
'name' => 'required|min_length[5]',
'email' => 'required|valid_email|is_unique[users.email]',
'password' => 'required|min_length[5]'
]);
if (!$inputs) {
return view('register', [
'validation' => $this->validator
]);
}
$this->user->save([
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email'),
'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
]);
session()->setFlashdata('success', 'Success! registration completed.');
return redirect()->to(site_url('/register'));
}
/**
* login form
*/
public function login()
{
return view('login');
}
/**
* login validate
*/
public function loginValidate()
{
$inputs = $this->validate([
'email' => 'required|valid_email',
'password' => 'required|min_length[5]'
]);
if (!$inputs) {
return view('login', [
'validation' => $this->validator
]);
}
$email = $this->request->getVar('email');
$password = $this->request->getVar('password');
$user = $this->user->where('email', $email)->first();
if ($user) {
$pass = $user['password'];
$authPassword = password_verify($password, $pass);
if ($authPassword) {
$sessionData = [
'id' => $user['id'],
'name' => $user['name'],
'email' => $user['email'],
'loggedIn' => true,
];
$this->session->set($sessionData);
return redirect()->to('dashboard');
}
session()->setFlashdata('failed', 'Failed! incorrect password');
return redirect()->to(site_url('/login'));
}
session()->setFlashdata('failed', 'Failed! incorrect email');
return redirect()->to(site_url('/login'));
}
/**
* Dashboard
* @param NA
*/
public function dashboard()
{
return view('dashboard');
}
/**
* User logout
* @param NA
*/
public function logout()
{
$session = session();
$session->destroy();
return redirect()->to('login');
}
}
- In the above code, I have created a constructor first. Then inside the constructor loaded the helper functions.
- Inside the register() method, I loaded the user registration form view.
- Next, we have the create() method. This method will validate the inputs and then will insert the values into the users table using the User model.
- After that we have the login() method to load the Codeigniter login form view.
- To validate the login functionality, we have the loginValidate() function. This will check the registered email first. If email found then it will check it’s password. We stored the password in the hash format. So, while checking the password on login we did use the password_verify() method. This will compare the hash password.
- There is dashboard() function to load a dashboard view after login.
- Lastly, we have the logout() function to clear the session and redirect to the login page again.
Upload Multiple Image with Validation in Codeigniter 4
Create Routes For Codeigniter
For managing the URL with respect to the above controller function, we will require the routes. For adding the route, you will need to switch to the app/Config folder. Now, add the below routes.
$routes->get('register', 'UserController::register');
$routes->post('register', 'UserController::create');
$routes->get('login', 'UserController::login');
$routes->post('login', 'UserController::loginValidate');
$routes->get('dashboard', 'UserController::dashboard', ['filter' => 'auth']);
$routes->get('logout', 'UserController::logout');
You may notice one thing in the dashboard route. That is filter and auth. Let me explain about it.
We are managing the session post successful login. Also, there is the logout function that will destroy the current session. But we want that after logout, the user shouldn’t redirect back to the dashboard page. That means the dashboard URL can be accessed only when the user is logged in.
So, destroying the session is not the solution to prevent the redirection back or from the URL directly. Hence, we will create a middleware (If you are familiar with Laravel). Here in the Codeigniter, it provides filter function that we will discuss here.
How to Upload Image and File in Codeigniter 4 with Validation
Create Filter in Codeigniter 4
For creating a filter, you have to navigate to the app/Filters folder. Now, create a new file that is Auth.php. You may create the file with any name. Then add the below code there.
<?php
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class Auth implements FilterInterface {
// before function
public function before(RequestInterface $request, $arguments = null) {
if(!session()->get('loggedIn')){
return redirect()->to('/login');
}
}
// after function
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) {
}
}
The above class implemented the FilterInterface. The before() function will be called automatically before the function gets called through the route. Inside this function, I have checked if the session has loggedIn value. Actually, we set loggedIn to true after the successful login. So, here, if the user is logged in and the session is active then it will return 1 (true). Otherwise, it will redirect the request to the login route.
In the next step, the Filter (middleware) will need to register so that it can be applied to the route level.
Register Filter (Middleware) in CodeIgniter 4
To register the created filter class, you will need to navigate to the app/Config/Filters.php file. Now, look for the aliases array. Initially, it will be looking like this.
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
];
Now, you have to add the Auth class here as showing below.
<?php
namespace Config;
use App\Filters\Auth;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\Honeypot;
class Filters extends BaseConfig
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array
*/
public $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'auth' => Auth::class,
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array
*/
public $globals = [
'before' => [
// 'honeypot',
// 'csrf',
],
'after' => [
'toolbar',
// 'honeypot',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'post' => ['csrf', 'throttle']
*
* @var array
*/
public $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array
*/
public $filters = [];
}
Now, let’s come to the view rendering.
Create Views For CodeIgniter Login and Register
We will create the below views inside the app/Views folder.
- register.php
- login.php
- dashboard.php
For creating the login and register form, I have used Bootstrap 5. So, let’s create the views and add the snippet one by one.
<!doctype html>
<html lang="en">
<head>
<title>User Registration and Login in Codeigniter 4</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container-fluid py-4">
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 col-md-12 col-sm-12 col-12 m-auto">
<?php
if (session()->getFlashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('success') ?>
</div>
<?php elseif (session()->getFlashdata('failed')) : ?>
<div class="alert alert-danger alert-dismissible">
<button type="button" class="btn-close" data-bs-dismiss="alert">×</button>
<?php echo session()->getFlashdata('failed') ?>
</div>
<?php endif; ?>
<?php $validation = \Config\Services::validation(); ?>
<form action="<?= base_url('register') ?>" method="post">
<?= csrf_field() ?>
<div class="card">
<div class="card-header">
<h5 class="card-title">Registration </h4>
</div>
<div class="card-body p-5">
<div class="form-group">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control <?php if ($validation->getError('name')) : ?>is-invalid<?php endif ?>" name="name" id="name" placeholder="Name" value="<?php echo set_value('name'); ?>" />
<?php if ($validation->getError('name')) : ?>
<div class="invalid-feedback">
<?= $validation->getError('name') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group pt-3">
<label for="email"> Email </label>
<input type="text" class="form-control <?php if ($validation->getError('email')) : ?>is-invalid<?php endif ?>" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>" />
<?php if ($validation->getError('email')) : ?>
<div class="invalid-feedback">
<?= $validation->getError('email') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group pt-3">
<label for="password"> Password </label>
<input type="password" class="form-control <?php if ($validation->getError('password')) : ?>is-invalid <?php endif ?>" name="password" placeholder="Password" value="<?php echo set_value('email'); ?>" />
<?php if ($validation->getError('password')) : ?>
<div class="invalid-feedback">
<?= $validation->getError('password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group pt-5 d-flex justify-content-between align-items-center">
<button type="submit" class="btn btn-success">Register</button>
<p class="d-flex justify-content-between align-items-center m-0"> Already registered? <a href="<?= base_url('login') ?>" class="nav-link"> Login </a> </p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</body>
</html>
In the register.php view, we have a form with some inputs like name, email, and password. Also, we displayed the validation error message.
<!doctype html>
<html lang="en">
<head>
<title>User Registration and Login in Codeigniter 4</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<div class="container-fluid py-4">
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 col-md-12 col-sm-12 col-12 m-auto">
<?php $validation = \Config\Services::validation(); ?>
<form action="<?= base_url('login') ?>" method="post">
<?= csrf_field() ?>
<div class="card">
<div class="card-header">
<h5 class="card-title">Login </h4>
</div>
<div class="card-body p-5">
<div class="form-group pt-3">
<label for="email"> Email </label>
<input type="text" class="form-control <?php if ($validation->getError('email')) : ?>is-invalid<?php endif ?>" name="email" placeholder="Email" value="<?php echo set_value('email'); ?>" />
<?php if ($validation->getError('email')) : ?>
<div class="invalid-feedback">
<?= $validation->getError('email') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group pt-3">
<label for="password"> Password </label>
<input type="password" class="form-control <?php if ($validation->getError('password')) : ?>is-invalid <?php endif ?>" name="password" placeholder="Password" value="<?php echo set_value('email'); ?>" />
<?php if ($validation->getError('password')) : ?>
<div class="invalid-feedback">
<?= $validation->getError('password') ?>
</div>
<?php endif; ?>
</div>
<div class="form-group pt-5 d-flex justify-content-between align-items-center">
<button type="submit" class="btn btn-success">Login</button>
<p class="d-flex justify-content-between align-items-center m-0"> Not have an account? <a href="<?= base_url('register') ?>" class="nav-link"> Register </a> </p>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</body>
</html>
Similarly, in the login.php file, we have the email and password field for the login. After the successful login, you will be redirected to the dashboard page. So, here is a basic navbar with the session value in the dashboard.
<!doctype html>
<html lang="en">
<head>
<title>User Registration and Login in Codeigniter 4</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
</head>
<body>
<?php $session = \Config\Services::session(); ?>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid ps-5">
<a class="navbar-brand" href="#">Programming Fields</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<li class="nav-item pe-5">
<a class="nav-link active" aria-current="page">Welcome: <?= $session->get('name'); ?> </a>
</li>
<li class="nav-item">
<a class="nav-link active" aria-current="page" href="<?= base_url('logout') ?>">Logout</a>
</li>
</ul>
</div>
</div>
</nav>
<div class="container-fluid py-4">
<div class="row mt-4">
<div class="col-xl-6 col-lg-6 col-md-12 col-sm-12 col-12 m-auto">
<h4 class="text-center"> Dashboard </h4>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
</body>
</html>
Now, that’s it for the functionality part. It’s time to check the result.
Form Validation Example in Codeigniter 4 For Beginners
Result of Register, Login, Logout with Session
Let’s run the application using spark serve command in the terminal.
php spark serve
Open the browser and start with the register route. You will have the below result. There is one login link to redirect to the login page.
Register Functionality Result
We already added the validation on the inputs. So, you may see the validation error message.
Once the validation passed, you may register. In the response, you will get the below result.
Login Functionality Result
Now, switch to the login route. You will have the below Codeigniter login form.
Here, in the Codeigniter login form, there is the validation. So, you may see the validation error message.
In case, if you enter an incorrect email that is not registered in the database. Then you will get the below error message.
Similarly, we have the incorrect password result, if you enter the wrong password.
After the successful login, you will be redirected to the dashboard page.
In the dashboard page, there is a logout option at the top right in the navbar. Also, the logged user name is displaying using the session. When you will click on the logout, it will destroy the session first. Then it will redirect to the login page.
Also, it won’t allow you to redirect back to the login page after destroying the session.
Conclusion
That’s it for the Codeigniter login and sign up with session functionality. We created a very basic registration form for the user. After the validation passed you will be able to register. Similarly, on the login page, we set the email and password for the login credentials. We managed the session for the logged user. The session helper is used to set the values in the session. So, I hope this post will help you in creating the Codeigniter login and sign up functionality.
sankalp says
I’m gettting an error which tells that :
Class “Config\Auth” not found
Umesh Rana says
Did you create Filter class? Please follow the steps, you missed to create Auth.php filter class in App/Filters folder.
Manoj says
I have done all these things and when i logged out and try to fetch dashboard through url its redirecting to me in login page its good and working fine but when i logged in with correct user id and password its again redirect to me login page.
why this happening i dont know. i have check also my session id value is there. iam using CI4.1.5 version
thanks
Senzaura says
Hey, I try to dumped the scheme of table too with using, “php spark migrate” instead success, it says Unable to connect to the database.
Main connection [MySQLi]: Access denied for user ‘****’@’localhost’ (using password: YES)
Any help?
Umesh Rana says
Please make sure you have updated the DB configuration correctly before migrating the database schema.