Dj Techblog

A blog on web development

Register user with admin approval in Codeigniter 4

Last modified on Oct 17, 2021
Register user with admin approval in Codeigniter-4

In my last tutorial I have discussed how to make an login register system with Codeigniter 4. In this tutorial I will discuss how to make an admin panel in Codeigniter 4, Bootstrap 5 and javascript where one can approve or reject incoming users registration. Approved users will be sent an email and rejected users will be deleted.

We start with making a register form where user can enter details. The details wiill be saved in a temporary new user table and at the same time a request will appear on admin panel to allow or reject the new user. On admin approval the user details will be transferred to another registered user table and the entry in the new user table will be automatically deleted. An email will also be sent to the user notifying successful registration. And, if admin rejects the new user the entry from the new user table will be discarded.

We will follow these basic steps to complete this project:

  1. Create a permanent and temporary table for user data.
  2. Create a register user form.
  3. Save the details in a temporary new-user table.
  4. Display incoming user requests on admin panel.
  5. Allow the admin to approve or reject incoming users.
  6. Delete the rejected user details from temporary table.
  7. Insert approved user data to permanent table.

The complete process can be divided into following steps:

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

Create permanent Table

     CREATE TABLE `ecommerce`.`user` ( `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;           
            

Create temporary Table

     CREATE TABLE `ecommerce`.`new-user-request` ( `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\UserModel;
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 UserModel();
        
        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');
    }

    public function viewusers(){
        
        $model = new UserModel();
        $data = [
            'users' => $model-> getUser(),
            'title' => 'View Users'
        ];

        echo view('templates/admin-header',$data);
        echo view('admin/view-users', $data);
        echo view('templates/admin-sidebar');
        echo view('templates/admin-footer');
        
    }

    public function newuserrequests(){
        
        $model = new NewUserModel();
        $data = [
            'users' => $model-> getNewUser(),
            'title' => 'New Users requsts'
        ];

        echo view('templates/admin-header', $data);
        echo view('admin/new-user-requests', $data);
        echo view('templates/admin-sidebar');
        echo view('templates/admin-footer');
        
    }

    function reject(){
        
        $username = $_POST['username'];
        $model = new NewUserModel();
        $model -> where('username',$username)->delete();
        echo 1;
    }

    function approve(){
        
        $username = $_POST['username'];
        $model1 = new NewUserModel();
        $model2 = new UserModel();
        $data = $model1->where('username', $username)->first();

        $fname = $data['fname'];
        $lname = $data['lname'];
        $mobile = $data['mobile'];
        $email = $data['email'];
        $pass = $data['password'];
        $role = $data['role'];

        $model2->save([
            'username' => $username,
            'fname' => $fname,
            'lname' => $lname,
            'mobile' => $mobile,
            'email' => $email,
            'password' => $pass,
            'role' => $role 
        ]);
        $model1 -> where('username',$username)->delete();

        echo 1;
    }
}    
            

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 logout() method logs the user out of the system.

The viewusers()function displays all the users in the system.

The newuserrequests()function displays all the incoming users to the system.

The approve()and reject() function will approve and reject the new incoming users respectively.

3. Create two models NewUserModel.php and UserModel.php

NewUserModel.php

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

UserModel.php

<php namespace App\Models;
 
    use CodeIgniter\Model;
     
    class UserModel 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.

Inside /Views/templates we will make following files admin-header.php, admin-sidebar.php, admin-footer.php

admin-header.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><?= esc($title) ?></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">
<link async defer rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- JavaScript Bundle with Popper -->
<script async defer 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>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<style>
    .sidenav
    {
        height: calc(100% - 67px);
        width: 220px;
        margin-top: 10px;
        float: left;
        position: fixed;
        overflow-y: scroll;
        bottom: 0;
        background: white;
        padding-top: 1px;
        z-index: 0;
        transition: ease width 2s;
    }
    
    .fw{
        font-size: 26px;
        cursor: pointer;
    }
    .menu{
        height: 70px;
        
    }
    .sub-text{
        font-size: 33px;
    }
    .sub-menu{
        height: 50px;
        
    }
    .sub-menu-text{
        margin-left: 20px;
        font-size: 25px;
        font-weight: bold;
    }
    
    .body{
        margin-left: 220px;
    }
    .body1{
        margin-left: 360px;
        margin-top: 50px;
    }
    .body2{
        margin-left: 150px;
        margin-top: 50px;
    }
</style>
</head>
<body>
        <script>
            function myFunction()
            {
                var header = document.getElementById("myHeader");
                var header1 = document.getElementById("bdy");
                var header2 = document.getElementById("bdy1");
                if(header.style.display === 'none'){
                    header.style.display = 'block';
                    header1.classList.add('body');
                    header2.classList.add('body1');
                    header2.classList.remove('body2');
                }
                else{
                    header.style.display = 'none';
                    header1.classList.remove('body');
                    header2.classList.remove('body1');
                    header2.classList.add('body2');

                }
            }
            
        </script>
        <div class="menu bg-light fixed-top ">
            <div class="row pb-1">
                <div class="col-sm-3">
                    <i class="fas fa-bars fw text-primary pt-2 pb-4 ps-3 " onclick="myFunction()"><span class="ps-3 sub-text text-primary fw-bold"> Admin Dashboard</span></i>
                </div>
                <div class="col-sm-6">
                    <div class="input-group mb-3 w-75 pt-2">
                        <input type="text" class="form-control" placeholder="Search" aria-label="Recipient's username" aria-describedby="basic-addon2">
                        <span class="input-group-text" id="basic-addon2">Search</span>
                    </div>
                </div>
                <div class="col-sm-1">
                    <i class="fa fa-bell fw pt-3"></i>
                </div>
                <div class="col-sm-1">
                    <i class="fas fa-user-cog fw pt-3"></i>
                </div>
                <div class="col-sm-1">
                    <a href="/user/logout"><i class="fas fa-sign-out-alt fw pt-3"></i></a>
                </div>
                
            </div>
            <div class="body" id="bdy">
                    
                    <div class="sub-menu sticky-top text-light pt-2 bg-primary">
                        
                           <p class="sub-menu-text"><?= esc($title) ?></p>
                    </div>
            </div>
        </div>
             

admin-sidebar.php

<div class="sidenav bg-primary" id="myHeader">
                <p class="pt-4 pb-2 text-center">
                    <a href="dashboard" class="text-decoration-none"><span class="text-light"><i class="fas fa-home"></i> Home</span></a>
                </p>    
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="categories" class="text-decoration-none"><span class="text-light"><i class="fas fa-list-alt"></i> Categories</span></a>
                </p>
                
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="products" class="text-decoration-none"><span class="text-light"><i class="fas fa-gift"></i> Products</span></a>
                </p>
                
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="new-user-requests" class="text-decoration-none"><span class="text-light"><i class="fas fa-user-plus"></i> New user requests</span></a>
                </p>
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="view-users" class="text-decoration-none"><span class="text-light"><i class="fas fa-users"></i> View users</span></a>
                </p>                
                <hr class="bg-light ">
                <p class="pt-2 pb-2 text-center">
                    <a href="view-orders" class="text-decoration-none"><span class="text-light"><i class="fab fa-first-order"></i> View Orders</span></a>
                </p>
    </div>
             

Inside /Views/admin we will make following files new-user-requests.php and view-users.php.

new-user-requests.php

              <div class="body1 pt-5" id="bdy1">
              <div class="w-100 mx-auto pt-5">
                <span class="text-danger">
                <?= \Config\Services::validation()->listErrors() ?>
                </span>
                       
                <div class="pt-3">
                      <?php if (! empty($users) && is_array($users)) : ?>
                          <div class="table table-responsive">
                            <table class="table table-striped w-75">
                              <thead>
                                <tr>
                                  <th class="text-left">Username</th>
                                  <th class="text-left">Firstname</th>
                                  <th class="text-left">Lastname</th>
                                  <th class="text-left">Mobile</th>
                                  <th class="text-left">Email</th>
                                  <th class="text-left">Action</th>
                                </tr>
                              </thead>
                              <tbody>
                              <?php foreach ($users as $user): ?>
                                <tr>
                                  <td><?= esc($user['username']) ?></td>
                                  <td><?= esc($user['fname']) ?></td>
                                  <td><?= esc($user['lname']) ?></td>
                                  <td><?= esc($user['mobile']) ?></td>
                                  <td><?= esc($user['email']) ?></td>
                                  <td><button type="button" class="btn btn-outline-danger btn-sm rjt" data-id="<?= esc($user['username']) ?>">Reject</button>
                                      <button type="button" class="btn btn-outline-primary btn-sm apr" data-id="<?= esc($user['username']) ?>">Approve</button>
                                  </td>
                                </tr>
                                <?php endforeach; ?>
                              </tbody>
                            </table> 
                          </div>  
                      <?php else : ?>

                        <h3>No new users</h3>
                    <?php endif ?>
                </div>
                        
                   </div>
               </div>  
</div>

                        <script> 
                            $(".rjt").click(function(){
                               var x =  $(this).attr("data-id");
                               var input = {
                                 "username" : x
                               };
                               $.ajax({
                                url : '<?php echo site_url('/admin/reject-user')?>',
                                type : 'POST',
                                dataType: 'json',
                                data : input,
                                success : function(response){
                                  location.reload();
                                  
                                },
                                error : function(){
                                  $('.error').html("Error").show();
                                }
                               });                               
                           });
                        </script>

                        <script> 
                            $(".apr").click(function(){
                               var x =  $(this).attr("data-id");
                               var input = {
                                 "username" : x
                               };
                               $.ajax({
                                url : '<?php echo site_url('/admin/approve-user')?>',
                                type : 'POST',
                                dataType: 'json',
                                data : input,
                                success : function(response){
                                  location.reload();
                                  
                                },
                                error : function(){
                                  $('.error').html("Error").show();
                                }
                               });                               
                           });
                        </script>
             

view-users.php


              <div class="body1 pt-5" id="bdy1">
              <div class="w-100 mx-auto pt-5">
                <span class="text-danger">
                <?= \Config\Services::validation()->listErrors() ?>
                </span>
                       
                <div class="pt-3">
                      <?php if (! empty($users) && is_array($users)) : ?>
                          <div class="table table-responsive">
                            <table class="table table-striped w-75">
                              <thead>
                                <tr>
                                  <th class="text-left">Username</th>
                                  <th class="text-left">Firstname</th>
                                  <th class="text-left">Lastname</th>
                                  <th class="text-left">Mobile</th>
                                  <th class="text-left">Email</th>
                                </tr>
                              </thead>
                              <tbody>
                              <?php foreach ($users as $user): ?>
                                <tr>
                                  <td><?= esc($user['username']) ?></td>
                                  <td><?= esc($user['fname']) ?></td>
                                  <td><?= esc($user['lname']) ?></td>
                                  <td><?= esc($user['mobile']) ?></td>
                                  <td><?= esc($user['email']) ?></td>
                                </tr>
                                <?php endforeach; ?>
                              </tbody>
                            </table> 
                          </div>  
                      <?php else : ?>

                        <h3>No Users</h3>
                    <?php endif ?>
                </div>
                        
                   </div>
               </div>  
</div>
             

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']);
        $routes->get('/admin/view-users', 'Home::viewusers',['filter' => 'auth']);
        $routes->get('/admin/new-user-requests', 'Home::newuserrequests',['filter' => 'auth']);
        $routes->match(['get', 'post'],'/admin/reject-user', 'Home::reject',['filter' => 'auth']);
        $routes->match(['get', 'post'],'/admin/approve-user', 'Home::approve',['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.