Codeigniter 4 Login and Registration Auth System Tutorial

Codeigniter 4 Login and Registration Auth System Tutorial

Codeigniter 4 login and registration authentication tutorial; In this bit by bit tutorial, you will learn how to build a login and registration authentication in Codeigniter 4 application. You will also learn how to implement a route filter to protect routes in the Codeigniter app.

A web application is a collection of various small features; every module is responsible for handling a specific type of task. In this CodeIgniter auth example, we will show you how to create a basic auth system in Codeigniter from scratch.

In this auth app, you will create login and registration forms to handle the user registration and login authentication process.

On the other hand, you will also figure out how to use filters to manage access on particular routes; this auth feature will make your application safer and secure; most importantly will refrain non authenticated users to access your app.

How to Create Registration and Login Auth System in CodeIgniter 4

  • Step 1: Download Codeigniter Project
  • Step 2: Create Database with Table
  • Step 3: Update Database Details
  • Step 4: Set Up User Model
  • Step 5: Build Controller Files
  • Step 6: Create Auth Routes
  • Step 7: Add Route Guard
  • Step 8: Create View File
  • Step 9: Run Development Server

Download Codeigniter Project

To start with, first open terminal window, add command then press enter to download the latest Codeigniter application.

composer create-project codeigniter4/appstarter

Also, you may install Codeigniter app manually from the website.

Create Database with Table

In this section, you need to create a database in MySQL database and table with user properties; here is the command you have to execute from the SQL tab.

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'name',
  `email` varchar(100) NOT NULL COMMENT 'email',
  `password` varchar(100) NOT NULL COMMENT 'password',
  `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='users auth list';

Update Database Details

To create a database connection with the Codeigniter, you have to go to app/Config/Database.php and add the database information into the DB file.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Set Up User Model

In this section, you have to first move to the app/Models directory; within this folder, you have to create a UserModel.php file, furthermore put the given code into it app/Models/UserModel.php file.

<?php 

namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = [
      'name',
      'email',
      'password',
      'created_at'
    ];
}

Build Controller Files

Create the RegisterController.php controller file in the app/Controllers folder, and this class will validate and register the new user in the Codeigniter app.

Update code in app/Controllers/RegisterController.php file.

<?php 

namespace App\Controllers;  
use CodeIgniter\Controller;

use App\Models\UserModel;

  
class RegisterController extends Controller
{
    public function index()
    {
        helper(['form']);
        $data = [];
        echo view('user_register', $data);
    }
  
    public function store()
    {
        helper(['form']);
        $rules = [
            'name'          => 'required|min_length[2]|max_length[50]',
            'email'         => 'required|min_length[4]|max_length[100]|valid_email|is_unique[users.email]',
            'password'      => 'required|min_length[4]|max_length[50]',
            'confirmpassword'  => 'matches[password]'
        ];
          
        if($this->validate($rules)){
            $model = new UserModel();
            $data = [
                'name'     => $this->request->getVar('name'),
                'email'    => $this->request->getVar('email'),
                'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
            ];
            $model->save($data);
            return redirect()->to('/login');
        }else{
            $data['validation'] = $this->validator;
            echo view('user_register', $data);
        }
          
    }
  
}

In this section, you need to create the LoginController.php file in the app/Controllers directory, then add the provided code into the app/Controllers/LoginController.php file.

<?php 

namespace App\Controllers;  
use CodeIgniter\Controller;
use App\Models\UserModel;
  

class LoginController extends Controller
{
    public function index()
    {
        helper(['form']);
        echo view('login');
    } 
  
    public function signin()
    {
        $session = session();
        $model = new UserModel();

        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        
        $data = $model->where('email', $email)->first();
        
        if($data){
            $pass = $data['password'];
            $pwd_verify = password_verify($password, $pass);
            if($pwd_verify){
                $ses_data = [
                    'id' => $data['id'],
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'isSignedIn' => TRUE
                ];

                $session->set($ses_data);
                return redirect()->to('/dashboard');
            }else{
                $session->setFlashdata('msg', 'wrong password.');
                return redirect()->to('/login');
            }
        }else{
            $session->setFlashdata('msg', 'wrong email.');
            return redirect()->to('/login');
        }
    }
}

In this section, you have to create the controller file; after that, append all the code into the app/Controllers/DashboardController.php file.

<?php 

namespace App\Controllers;  
use CodeIgniter\Controller;

  
class DashboardController extends Controller
{
    public function index()
    {
        $session = session();
        echo "Hey User : ".$session->get('name');
    }

}

Add Route Guard

In this step, you will learn how to use filter service, and it is a helpful service to validate before and after requests.

We have created a dashboard page, this page is the main page of the app, and we want our users only to access this page when they are logged in.

Create RouteFilter.php inside the app/Filters folder, then insert the code into a app/Filters/RouteFilter.php file.

<?php 

namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;


class RouteFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        if (!session()->get('isSignedIn'))
        {
            return redirect()
                ->to('/login');
        }
    }
    
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        
    }
}

Open app/Config/Filters.php file, find $aliases array in the Filters class and switch the aliases prop with given code.

public $aliases = [
		'csrf'     => CSRF::class,
		'toolbar'  => DebugToolbar::class,
		'honeypot' => Honeypot::class,
		'routeFilter' => \App\Filters\RouteFilter::class,
	];

Create Auth Routes

Head over app/Config/Routes.php file, open the file and one by one insert the routes inside the suggested file.

The /dashboard page is not accessible due to injecting the route guard filter.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->setDefaultController('RegisterController');
$routes->get('/', 'RegisterController::index');
$routes->get('/register', 'RegisterController::index');
$routes->get('/login', 'LoginController::index');
$routes->get('/dashboard', 'DashboardController::index',['filter' => 'routeFilter']);

Create View File

In this step, you have to create a user_register.php file; you have to define the user registration logic in this file. So, add the code into the app/Views/user_register.php file.

<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>User Registration in Codeigniter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-6">
                <h3>Sign Up</h3>
                <?php if(isset($validation)):?>
                <div class="alert alert-info">
                   <?= $validation->listErrors() ?>
                </div>
                <?php endif;?>

                <form action="<?php echo base_url(); ?>/RegisterController/store" method="post">
                    <div class="mb-3">
                        <input type="text" name="name" placeholder="Name" value="<?= set_value('name') ?>" class="form-control" >
                    </div>

                    <div class="mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>

                    <div class="mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>

                    <div class="mb-3">
                        <input type="password" name="confirmpassword" placeholder="Confirm Password" class="form-control" >
                    </div>

                    <button type="submit" class="btn btn-danger">Register</button>
                </form>
            </div>
        </div>
    </div>
</body>

</html>

In this section, you ought to create a login.php file; and define the user login code into the file.

Update the code into the app/Views/login.php file.

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Codeigniter User Login Example</title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-6">
                <h3>SignIn</h3>
                <?php if(session()->getFlashdata('msg')):?>
                    <div class="alert alert-info">
                       <?= session()->getFlashdata('msg') ?>
                    </div>
                <?php endif;?>

                <form action="<?php echo base_url(); ?>/LoginController/signin" method="post">
                    <div class="mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>

                    <div class="mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>
                    
                    <button type="submit" class="btn btn-dark">Login</button>
                </form>
            </div>
              
        </div>
    </div>
  </body>
</html>

Run Development Server

In the last segment, you have to run the application, and you can register the user and then login to the app.

If you are not a registered user, then you won’t be able to access the dashboard page.

php spark serve
http://localhost:8080/register-user

http://localhost:8080/login

http://localhost:8080/dashboard

Summary

This guide showed the conclusive ways to build a simple authentication system in the Codeigniter app. Moreover, you have also learned how to set a session variable in Codeigniter.

In this complete walkthrough of the Codeigniter user login and registration example, We built a simple auth system.

Codeigniter is an incredible framework. It is powerful and applicable in many domains. It is used for creating robust applications and highly effective in the web development process.