Dj Techblog

A blog on web development

Login and Register sytem in Codeigniter 4 - Beginners Tutorial

Last modified on Oct 17, 2021
Login and register system in codeigniter 4 tutorial for beginners

In this tutorial we will see how to build a simple Login and Register system using php framework Codeigniter 4. Before we start we need to have a basic understanding of how Controller, Model and Views work in a model-view architecture built using Codeigniter 4.

Login and register system built with Codeigniter 4 php framework is effective and secured in many ways. The Security class in Codeigniter 4 contains methods that help protect sites against Cross-Site Request Forgery attacks. So, it provides lots of benefits in comparison to php. The php framework also provides lots of built in function that eases to work with database.

The complete process can be divided into following steps:

  1. Create database.
  2. Create Controller functions for login and register.
  3. Create Models to handle database.
  4. Create Views for login and register
  5. Create Routes.
  6. Validate routes with Filters

1. Create a database 'ecommerce' with table name 'users'

Create Table

     CREATE TABLE `ecommerce`.`users` ( `username` VARCHAR(20) NOT NULL , 
     `fname` TEXT NOT NULL , `lname` TEXT NOT NULL , 
     `mobile` BIGINT NOT NULL , `email` TEXT NOT NULL , `password` INT NOT NULL , 
     `role` INT NOT NULL , PRIMARY KEY (`username`(20))) ENGINE = InnoDB;           
            

2. Create a Home.php inside the Controllers.

Home.php

<?php

    namespace App\Controllers;
    use App\Models\NewUserModel;
    use CodeIgniter\Controller;
    
    class Home extends BaseController
    {

        public function index(){
            echo view('index');
        }
        
        public function register(){

            $model = new NewUserModel();
            
            if ($this->request->getMethod() === 'post' && $this->validate([
                
                'username' => 'required',
                'fname' => 'required',
                'lname' => 'required',
                'mobile' => 'required',
                'email' => 'required',
                "password" => 'required'
    			
            ]))
            {
                $model->save([
                    'username' => $this->request->getPost('username'),
                    'fname' => $this->request->getPost('fname'),
                    'lname' => $this->request->getPost('lname'),
                    'mobile' => $this->request->getPost('mobile'),
                    'email' => $this->request->getPost('email'),
                    'password' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
                    'role' => 0
                    
                ]);
    
                echo view('user/login');
    
            }
            else
            {
                
                echo view('user/register');
                
            }
        }
    
        public function auth(){
    
            $session = session();
            
            $model = new NewUserModel();
            
            if ($this->request->getMethod() === 'post' && $this->validate([
                
                'username' => 'required',
                "password" => 'required'
    			
            ]))
            {
                $username = $this->request->getPost('username');
                $password = $this->request->getPost('password');
            
                $data = $model->where('username', $username)->first();
                if($data){
                    $pass = $data['password'];
                    $verify_pass = password_verify($password, $pass);
                    if($verify_pass){
                        $ses_data = [
                            'username'       => $data['username'],
                            'email'          => $data['email'],
                            'logged_in'     => TRUE
                        ];
                        $session->set($ses_data);
                        if(!$data['role'])
                            return redirect()->to('user/home');
                        else    
                            return redirect()->to('admin/dashboard');
                    }else{
                        $session->setFlashdata('msg', 'Wrong Password');
                        return redirect()->to('user/login');
                    }
                }else{
                    $session->setFlashdata('msg', 'Email not Found');
                    return redirect()->to('user/login');
                }
            }
            else
                echo view('user/login');
    
        }  
        
        public function login(){
            echo view('user/login');
        }
    
        public function dashboard(){
            $session = session();
            
            //echo "Welcome back, ".$session->get('user_name');
                echo view('user/home');
        }
    
        public function logout()
        {
            $session = session();
            $session->destroy();
            return redirect()->to('/user/login');
        }
    
        public function admindashboard(){
            $session = session();
            $data = [
                'session' => $session,
                'title' => "Home"
            ];
            
            //echo "Welcome back, ".$session->get('user_name');
                echo view('templates/admin-header',$data);
                echo view('admin/dashboard');
                echo view('templates/admin-sidebar');
                echo view('templates/admin-footer');
        }
}      
            

The Home.php is home to your different Controller functions which performs different jobs. It is mentioned one by one. It contains a index() method whose job is to display the index page that is home page of the website.

The next function you will see is a register() method. The function creates a object $model of NewUserModel class. The function checks for the mandatory field, and siaplays error to the user. The $model->save() actually save the values of the new user as a new row in the users table.

The auth() function basically authorizes the new user who try to login to the system. It takes the values from the login form and matches it with the every column in the table. If a match is found user is redirected to the Home page or Login failed message is displayed to the user.

The login() function display the login page to the user. And at last the logout() function logs the user out of the system.

3. Create a NewUserModel.php inside Models

NewUserModel.php

<?php namespace App\Models;
 
    use CodeIgniter\Model;
     
    class NewUserModel extends Model{
        protected $table = 'user';
        
        protected $allowedFields = ['username','fname','lname','mobile','email','password','role'];
    
        public function getUser(){
            return $this->findAll();
        }
    }            
            

4. Create views

We will create following files under Views. The index.html file is the home page of the system.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home Page</title>
    <!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
</head>
<body>
<h1 class="pt-5 text-center">Home Page</h1>

<h2 class="text-center pt-5"><a class="btn btn-primary" href="/user/register" >Register </a> <a class="btn btn-primary" href="/user/login">Login</a></h2>
</body>
</html>          
            

Inside /Views/user we will make following files one by one home.php, login.php, register.php

home.php

Create a demo file with this name in the mentioned path and just write one line inside it to denote it the user home.

login.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
</head>
<body>
        <div class="pt-5  w-50 mx-auto">
            <h1 class="text-center pb-5">Login user form</h1>
            <?= \Config\Services::validation()->listErrors() ?>
            <form class="form-control w-75 mx-auto" action="/user/login" method="post">
                <div class="mb-3">
                    <label for="exampleInputEmail1" class="form-label">Username</label>
                    <input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
                </div>
                <div class="mb-3">
                    <label for="exampleInputPassword1" class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1">
                </div>
                
                <button type="submit" class="btn btn-primary">Login</button>

                <div id="emailHelp" class="form-text pt-3 fw-bold">Not Registered? <a class="text-decoration-none" href="/user/register">Register</a></div>
            </form>
        </div>
</body>
</html>
             

register.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register</title>
    <!-- CSS only -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
<!-- JavaScript Bundle with Popper -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
</head>
<body>
        <div class="pt-5 w-50 mx-auto">
            <h1 class="text-center pb-5">Register user form</h1>
            <span class="text-danger"><?= \Config\Services::validation()->listErrors() ?></span>
        <form class="form-control w-75 mx-auto" method="post" action="/user/register">
                <div class="mb-3">
                    <label for="username" class="form-label">Username</label>
                    <input type="text" name="username" class="form-control" placeholder="Enter username" aria-describedby="emailHelp">
                    
                </div>
                <div class="mb-3">
                    <label for="fname" class="form-label">First Name</label>
                    <input type="text" name="fname" class="form-control" placeholder="Enter firstname" aria-describedby="emailHelp">
                    
                </div>
                <div class="mb-3">
                    <label for="lname" class="form-label">Last name</label>
                    <input type="text" name="lname" class="form-control" placeholder="Enter last name" aria-describedby="emailHelp">
                    
                </div>
                <div class="mb-3">
                    <label for="mobile" class="form-label">Monile No.</label>
                    <input type="text" name="mobile" class="form-control" placeholder="Enter 10 digit mobile number" aria-describedby="emailHelp">
                    
                </div>
                <div class="mb-3">
                    <label for="email" class="form-label">Email</label>
                    <input type="email" name="email" class="form-control" placeholder="Enter email" aria-describedby="emailHelp">
                    <div id="emailHelp" class="form-text">We'll never share your email with anyone else.</div>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">Password</label>
                    <input type="password" name="password" class="form-control" id="exampleInputPassword1">
                </div>
                <div class="mb-3">
                    <label for="password1" class="form-label">Confirm Password</label>
                    <input type="password" name="password1" class="form-control" id="exampleInputPassword2">
                </div>
                
                <button type="submit" class="btn btn-primary">Register</button>

                <div id="emailHelp" class="form-text pt-3 fw-bold">Already Registered? <a class="text-decoration-none" href="/user/login">Login</a></div>
        </form>
        </div>
</body>
</html>
             

Remember the index.html is inside the /Views and rest of the three file is inside /Views/user.

5. Create Routes

Open /Config/Routes.php and add following lines.

        $routes->get('/', 'Home::index');
        $routes->get('/user/register', 'Home::register');
        $routes->match(['get', 'post'], 'user/register', 'Home::register');
        $routes->get('/user/login', 'Home::login');
        $routes->get('/user/logout', 'Home::logout');
        $routes->match(['get', 'post'], 'user/login', 'Home::auth');
        $routes->get('/user/home', 'Home::dashboard',['filter' => 'auth']);
        $routes->get('/admin/dashboard', 'Home::admindashboard',['filter' => 'auth']);
            

6. validate Routes with Filters

Filters in Codeigniter are Classes that are used to validate a request before and after the Controller. It contains two methods before() and after() that is executed before and after the Controller. In this scenario, Filters are used to validate whether the user is logged in or not if any attempt are made by the user to access the home page without login. So, if a user access the url of the home page, it will be automatically redirected to login page.

Create a file Auth.php in Filters

Auth.php

<?php namespace App\Filters;
 
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
 
class Auth implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        // if user not logged in
        if(! session()->get('logged_in')){
            // then redirct to login page
            return redirect()->to('/user/login'); 
        }
    }
 
    //--------------------------------------------------------------------
 
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        // Do something here
    }
}          
            

Open the /Config/Filters.php and find the following codes.

                public $aliases = [
                        'csrf'     => CSRF::class,
                        'toolbar'  => DebugToolbar::class,
                        'honeypot' => Honeypot::class
                ];
            

and replace it with

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

Published on Oct 17, 2021


Ad section
Ad section

Intro

Debabratta Jena

I mainly write about HTML5, CSS3, Javascript, Angular JS, Ajax, PHP, Mysql, On page SEO, Google Ads, Tag manager, Universal Analytics, Google My Business, SERP, Apache server configuration etc, Yoga is my passion.

Reach to me in the contact us form below

Follow me on

Contact us

Subscribe

Tags

Php HTML5 Javascript CSS Ajax Angular JS Google My bisiness Listing Google tag Manager Google Universal Analytics Search Engine Optimization On page SEO Off page SEO Google Marketing platform Digital Marketing Google Ads Mysql Apache Server

Ad section
×

Subscribe to get email notification about our new post

Name

Email

We neither sell nor share your personal information with any third party. Your identity is safe with us.