Codeigniter 4 Authentication Login and Registration Tutorial

Last updated on: by Digamber

Codeigniter authentication system tutorial; If you are new to Codeigniter and don’t know how to create a basic CodeIgniter auth system, this guide will help you create login and registration in Codeigniter using step-by-step instructions.

In this Codeigniter auth tutorial, we will tell you how to create a simple auth system with login and signup functionalities. We will specifically use the Codeigniter session to store the state of authenticated users.

Login is a process where a user logs into your application using a registered email and password. After successfully logging into an application, a user can access the further resources of the application.

In contrast, signup is when users register themselves using the name, email, and password properties.

Codeigniter 4 Auth (Signin and Signup) System Example

  • Step 1: Create Codeigniter Project
  • Step 2: Display Errors
  • Step 3: Generate Table into Database
  • Step 4: Connect CI to Database
  • Step 5: Create and Update User Model
  • Step 6: Register Auth Controllers
  • Step 7: Create Auth View
  • Step 8: Protect Route with Filter
  • Step 9: Run CI Application

Create Codeigniter Project

There are two standard methods to download the codeigniter app.

You can invoke the command to download the Codeigniter app, though you must have Composer configured in your system.

composer create-project codeigniter4/appstarter

Second method is straightforward, visit Codeigniter site and download the Codeigniter application.

Display Errors

You may turn on the feature to errors, go to the app/Config/Boot/production.php and change display_errors prop value to 1 from 0.

ini_set('display_errors', '1');

Generate Table into Database

The primary archetype of auth table contains users table in the database with like name, email, password, and created_at properties. Head over to PHPMyAdmin, type the given SQL query and hit enter.

CREATE TABLE users (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(150),
    email VARCHAR(150),
    password VARCHAR(150),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;

Connect CI to Database

The existing step, describes how you can connect CI app to database, its amazingly facile process, add database name, username and password in app/Config/Database.php.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'codeigniter_db',
        '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,
    ];

Create and Update User Model

Further, create a new model file, and define the users table name and the values in the $table and $allowedFields. Create UserModel.php file in app/Models folder after that update the given code in app/Models/UserModel.php file.

<?php 
namespace App\Models;  
use CodeIgniter\Model;
  
class UserModel extends Model{
    protected $table = 'users';
    
    protected $allowedFields = [
        'name',
        'email',
        'password',
        'created_at'
    ];
}

Register Auth Controllers

A controller is a file that holds the functions and methods used to handle the application’s business logic; in this step, you have to create Signup and Signin controller files.

Create SignupController.php file in the app/Controllers directory, then insert the below code into the app/Controllers/SignupController.php file.

<?php 
namespace App\Controllers;  
use CodeIgniter\Controller;
use App\Models\UserModel;
  
class SignupController extends Controller
{
    public function index()
    {
        helper(['form']);
        $data = [];
        echo view('signup', $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)){
            $userModel = new UserModel();
            $data = [
                'name'     => $this->request->getVar('name'),
                'email'    => $this->request->getVar('email'),
                'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
            ];
            $userModel->save($data);
            return redirect()->to('/signin');
        }else{
            $data['validation'] = $this->validator;
            echo view('signup', $data);
        }
          
    }
  
}

Then, create ProfileController.php file in the app/Controllers folder, and place the suggested code in the app/Controllers/ProfileController.php file.

<?php 
namespace App\Controllers;  
use CodeIgniter\Controller;
  
class ProfileController extends Controller
{
    public function index()
    {
        $session = session();
        echo "Hello : ".$session->get('name');
    }
}

Lastly, create SigninController.php file in the app/Controllers directory, then insert the below code into the app/Controllers/SigninController.php file.

<?php 
namespace App\Controllers;  
use CodeIgniter\Controller;
use App\Models\UserModel;
  
class SigninController extends Controller
{
    public function index()
    {
        helper(['form']);
        echo view('signin');
    } 
  
    public function loginAuth()
    {
        $session = session();
        $userModel = new UserModel();
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        
        $data = $userModel->where('email', $email)->first();
        
        if($data){
            $pass = $data['password'];
            $authenticatePassword = password_verify($password, $pass);
            if($authenticatePassword){
                $ses_data = [
                    'id' => $data['id'],
                    'name' => $data['name'],
                    'email' => $data['email'],
                    'isLoggedIn' => TRUE
                ];
                $session->set($ses_data);
                return redirect()->to('/profile');
            
            }else{
                $session->setFlashdata('msg', 'Password is incorrect.');
                return redirect()->to('/signin');
            }
        }else{
            $session->setFlashdata('msg', 'Email does not exist.');
            return redirect()->to('/signin');
        }
    }
}

Create Auth View Templates

So far, we have followed every instruction to proliferate this Codeigniter auth system example, and now we have to define the view files.

Make sure to get inside the app/Views folder and create signin.php and signup.php files; these files will be used for login and user registration in Codeigniter.

Create the user registration form using Bootstrap 5 and tie with the method to handle the user registration, Open and place the code in the app/View/signup.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 Auth User Registration Example</title>
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-md-center">
            <div class="col-5">
                <h2>Register User</h2>
                <?php if(isset($validation)):?>
                <div class="alert alert-warning">
                   <?= $validation->listErrors() ?>
                </div>
                <?php endif;?>
                <form action="<?php echo base_url(); ?>/SignupController/store" method="post">
                    <div class="form-group mb-3">
                        <input type="text" name="name" placeholder="Name" value="<?= set_value('name') ?>" class="form-control" >
                    </div>
                    <div class="form-group mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>
                    <div class="form-group mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>
                    <div class="form-group mb-3">
                        <input type="password" name="confirmpassword" placeholder="Confirm Password" class="form-control" >
                    </div>
                    <div class="d-grid">
                        <button type="submit" class="btn btn-dark">Signup</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</body>
</html>

Next, ramp up the signin view template’s aesthetics, thus Open and place the code in the app/View/signin.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 Login with Email/Password Example</title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-md-center">
            <div class="col-5">
                
                <h2>Login in</h2>
                
                <?php if(session()->getFlashdata('msg')):?>
                    <div class="alert alert-warning">
                       <?= session()->getFlashdata('msg') ?>
                    </div>
                <?php endif;?>
                <form action="<?php echo base_url(); ?>/SigninController/loginAuth" method="post">
                    <div class="form-group mb-3">
                        <input type="email" name="email" placeholder="Email" value="<?= set_value('email') ?>" class="form-control" >
                    </div>
                    <div class="form-group mb-3">
                        <input type="password" name="password" placeholder="Password" class="form-control" >
                    </div>
                    
                    <div class="d-grid">
                         <button type="submit" class="btn btn-success">Signin</button>
                    </div>     
                </form>
            </div>
              
        </div>
    </div>
  </body>
</html>

Set + Protect Routes with Filter

In the next step, get inside the app/Config/Filters.php, look for $aliases array and replace the whole array with the recommended code.

	/**
	 * Configures aliases for Filter classes to
	 * make reading things nicer and simpler.
	 *
	*/
	public $aliases = [
		'csrf'     => \CodeIgniter\Filters\CSRF::class,
		'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
		'honeypot' => \CodeIgniter\Filters\Honeypot::class,
		'authGuard' => \App\Filters\AuthGuard::class,
	];

In the next step, create an AuthGuard.php file inside the app/Filters folder; this quintessential file will check if the user is logged in and redirect to the signin page if the user is not signed in.

Open and add code in app/Filters/AuthGuard.php file.

<?php 
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

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

Lastly, move towards routes file to create routes, we need to set routes to execute the controller functions. Similarly, protect the profile route, which will be restricted for un-authenticated users.

Get into the app/Config/Routes.php file and define the given routes into the file.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
 */
$routes->get('/', 'SignupController::index');
$routes->get('/signup', 'SignupController::index');
$routes->match(['get', 'post'], 'SignupController/store', 'SignupController::store');
$routes->match(['get', 'post'], 'SigninController/loginAuth', 'SigninController::loginAuth');
$routes->get('/signin', 'SigninController::index');
$routes->get('/profile', 'ProfileController::index',['filter' => 'authGuard']);

You have to remember one thing, look for following router below the “Route Definitions” section, make sure to remove or comment out following route; otherwise, wrong page will load when you’ll start the app.

// $routes->get('/', 'Home::index');

Run CI Application

Eventually, now you have landed on the last section of this tutorial, and we will advise you to use the given command to run the CI app.

php spark serve

You are ready to signup in Codeigniter, go ahead and use the provided url.

http://localhost:8080/signup

Codeigniter Authentication System

Conclusion

Throughout this journey, you have walked along with us and went through subtle nuances which were significantly helpful in implementing or building auth system in Codeigniter 4.

We learned how to create login or sign-in and registration or signup features in the Codeigniter application.

However, this was just the beginning of the Codeigniter login and signup example; you can extend and more components if required in the Codeigniter app.

You can download the full code of this tutorial from @GitHub

positronX.io - Tamso Ma Jyotirgamaya
Digamber

A Full-stack developer with a passion to solve real world problems through functional programming.