Codeigniter 4 Login Registration and Logout Example

CodeIgniter 4 login registration and logout example; In this tutorial, i will show you how to create authentication (login registration and logout functionality) in codeigniter 4 app.

For create login registration and logout in codeigniter 4 app, you have to use Bootstrap and MySQL DB with Codeigniter 4 framework. So in this CodeIgniter 4 authentication example, you have make login and registration in Codeigniter 4 using Mysql db and bootstrap. Here you can find step by step guide for how to create login registration and logout (authentication) in PHP Codeigniter 4 using Mysql and Bootstrap 4 library.

Nowadays every application must have an authenticated system. In that you will have some login, registration, forget password, reset password, change password and other packaged modules available. So, i am going to create codeigniter 4 login registration and logout system.

Create Login Registration and Logout System In Codeigniter 4

  • Install Codeigniter 4 Application
  • Basic App Configurations
  • Create Database and Table
  • Setup Database Credentials
  • Create Model Class
  • Create LoginRegistrationController Controller Class
  • Create Login, Registration and Dashboard Views
  • Setup Routes
  • Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE TABLE users(
    user_id INT PRIMARY KEY AUTO_INCREMENT,
    user_name VARCHAR(100),
    user_email VARCHAR(100),
    user_password VARCHAR(200),
    user_created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=INNODB;

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        '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,
	];

Step 5 – Create Model Class

Create UserModel.php file. So, visit app/Models/ directory and create UserModel.php.Then add the following code into it:

<?php 
namespace App\Models;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'users';
    protected $primaryKey = 'id';
    protected $allowedFields = ['user_name','user_email','user_password','user_created_at'];
}

Step 6 – Create LoginRegistrationController Controller Class

Create LoginRegistrationController.php file. So, visit app/Controllers directory and create LoginRegistrationController.php.Then add the following code into it:

<?php namespace App\Controllers;
 
use CodeIgniter\Controller;
use App\Models\UserModel;
 
class LoginRegisterController extends Controller
{
    public function index()
    {
        //include helper form
        helper(['form']);
        $data = [];
        echo view('register', $data);
    }
 
    public function save()
    {
        //include helper form
        helper(['form']);
        //set rules validation form
        $rules = [
            'name'          => 'required|min_length[3]|max_length[20]',
            'email'         => 'required|min_length[6]|max_length[50]|valid_email|is_unique[users.user_email]',
            'password'      => 'required|min_length[6]|max_length[200]',
            'confpassword'  => 'matches[password]'
        ];
         
        if($this->validate($rules)){
            $model = new UserModel();
            $data = [
                'user_name'     => $this->request->getVar('name'),
                'user_email'    => $this->request->getVar('email'),
                'user_password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT)
            ];
            $model->save($data);
            return redirect()->to('/login');
        }else{
            $data['validation'] = $this->validator;
            echo view('register', $data);
        }
         
    }
 
    public function login()
    {
        helper(['form']);
        echo view('login');
    } 
 
    public function auth()
    {
        $session = session();
        $model = new UserModel();
        $email = $this->request->getVar('email');
        $password = $this->request->getVar('password');
        $data = $model->where('user_email', $email)->first();
        if($data){
            $pass = $data['user_password'];
            $verify_pass = password_verify($password, $pass);
            if($verify_pass){
                $ses_data = [
                    'user_id'       => $data['user_id'],
                    'user_name'     => $data['user_name'],
                    'user_email'    => $data['user_email'],
                    'logged_in'     => TRUE
                ];
                $session->set($ses_data);
                return redirect()->to('/dashboard');
            }else{
                $session->setFlashdata('msg', 'Wrong Password');
                return redirect()->to('/login');
            }
        }else{
            $session->setFlashdata('msg', 'Email not Found');
            return redirect()->to('/login');
        }
    }
 
    public function logout()
    {
        $session = session();
        $session->destroy();
        return redirect()->to('/login');
    }

    public function dashboard()
    {
        $session = session();
        echo "Welcome back, ".$session->get('user_name');
    }

}

UserCrudController crud controller’s methods will work as follows:

  • The index() function renders the registration form template into the view.
  • The save() function add user into database.
  • The login() function renders the login from template into the view.
  • The auth() function authenticate user from database.
  • The logout() function destroy login user session.
  • The dashboard() function show welcome msg after login.

Step 7 – Create Login, Registration and Dashboard Views

In this step, visit app/Views/ and create some views files to display login and registration template.

Create registration.php view file, so visit app/views/ directory and create registration.php file. Then add the following HTML into registration.php file:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
 
    <title>Codeigniter 4 Register Example</title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-md-center">
 
            <div class="col-6">
                <h1>Sign Up</h1>
                <?php if(isset($validation)):?>
                    <div class="alert alert-danger"><?= $validation->listErrors() ?></div>
                <?php endif;?>
                <form action="/save" method="post">
                    <div class="mb-3">
                        <label for="InputForName" class="form-label">Name</label>
                        <input type="text" name="name" class="form-control" id="InputForName" value="<?= set_value('name') ?>">
                    </div>
                    <div class="mb-3">
                        <label for="InputForEmail" class="form-label">Email address</label>
                        <input type="email" name="email" class="form-control" id="InputForEmail" value="<?= set_value('email') ?>">
                    </div>
                    <div class="mb-3">
                        <label for="InputForPassword" class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" id="InputForPassword">
                    </div>
                    <div class="mb-3">
                        <label for="InputForConfPassword" class="form-label">Confirm Password</label>
                        <input type="password" name="confpassword" class="form-control" id="InputForConfPassword">
                    </div>
                    <button type="submit" class="btn btn-primary">Register</button>
                </form>
            </div>
             
        </div>
    </div>
     
    <!-- Popper.js first, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
  </body>
</html>

Next, Create login.php view file, so visit application/views/ directory and create login.php file. Then add the following HTML into login.php file:

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous">
 
    <title>Codeigniter 4 Login Example</title>
  </head>
  <body>
    <div class="container">
        <div class="row justify-content-md-center">
 
            <div class="col-6">
                <h1>Sign In</h1>
                <?php if(session()->getFlashdata('msg')):?>
                    <div class="alert alert-danger"><?= session()->getFlashdata('msg') ?></div>
                <?php endif;?>
                <form action="/postLogin/" method="post">
                    <div class="mb-3">
                        <label for="InputForEmail" class="form-label">Email address</label>
                        <input type="email" name="email" class="form-control" id="InputForEmail" value="<?= set_value('email') ?>">
                    </div>
                    <div class="mb-3">
                        <label for="InputForPassword" class="form-label">Password</label>
                        <input type="password" name="password" class="form-control" id="InputForPassword">
                    </div>
                    <button type="submit" class="btn btn-primary">Login</button>
                </form>
            </div>
             
        </div>
    </div>
     
    <!-- Popper.js first, then Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js" integrity="sha384-oesi62hOLfzrys4LxRF63OJCXdXDipiYWBnvTl9Y9/TRlw5xlKIEHpNyvvDShgf/" crossorigin="anonymous"></script>
  </body>
</html>

Step 8 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

//
$routes->setDefaultController('LoginRegisterController');
$routes->get('/', 'LoginRegisterController::index');
$routes->post('save', 'LoginRegisterController::save');
$routes->get('login', 'LoginRegisterController::login');
$routes->post('postLogin', 'LoginRegisterController::auth');
$routes->get('logout', 'LoginRegisterController::logout');
$routes->get('dashboard', 'LoginRegisterController::dashboard');

Step 9 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Conclusion

C odeigniter 4 login and registration with bootstrap and mysql example;In this tutorial, you have learned successfully how to create authentication (login registration and logout functionality) in codeigniter 4 app with bootstrap and mysql database.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 Image Crop and Save using Croppie Example
  15. Codeigniter 4 Dependent Dropdown using jQuery Ajax Example
  16. CodeIgniter 4 Rest Api CRUD Example

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *