Codeigniter 4 Authentication Login and Registration
The most common way of authenticating a user in web applications is through a login form. It is usually used to check the authenticity of the use. In this tutorial, we will create a Codeigniter 4 Authentication Login and Registration with MySQL. So here we have handled login functionality by creating a simple login form in CodeIgniter and Bootstrap Framework along with MySQL Database. This is a very simple example, you can just copy-paste and change according to your requirement.
Before started to implement the Codeigniter 4 Authentication Login and Registration, look files structure:
- codeigniter-authentication-login-registration
- app
- Config
- App.php
- Constants.php
- Database.php
- Routes.php
- Filters.php
- Filters
- AuthGuard.php
- Controllers
- User.php
- Models
- UserModel.php
- Views
- user
- register.php
- login.php
- dashboard.php
- templates
- header.php
- footer.php
- menus.php
- user
- Config
- public
- .htaccess
- index.php
- .htaccess
- .env
- assets
- images
- css
- style.css
- sticky-footer-navbar.css
- app
Step 1 – Install Codeigniter 4 Application
To handle the actual install you would use the following command in your terminal or visit Codeigniter site and download the Codeigniter application.
1 |
composer create-project codeigniter4/appstarter codeigniter-authentication-login-registration |
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.
1 |
ini_set('display_errors', '1'); |
Step 2 – Basic App Configurations
Now, you need to some basic configuration on the app/config/app.php file.
1 2 3 |
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/codeigniter-authentication-login-registration'; |
Step 3: Create the Database and Table
For this tutorial, you need a MySQL database with the following table:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php CREATE TABLE `users` ( `user_id` int(12) NOT NULL, `name` varchar(50) DEFAULT NULL, `user_name` varchar(50) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `status` int(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `users` ADD PRIMARY KEY (`user_id`), ADD UNIQUE KEY `email` (`email`); ALTER TABLE `users` MODIFY `user_id` int(12) NOT NULL AUTO_INCREMENT; COMMIT; ?> |
Step 4: Setup and Configure Database access
Update the file app/Config/Database.php OR .env file:
i) .env
1 2 3 4 5 |
database.default.hostname = localhost database.default.database = demo_DB database.default.username = root database.default.password = root database.default.DBDriver = MySQLi |
ii) Database.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php // configure database public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => '', 'password' => '', 'database' => '', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ]; ?> |
Step 5: Create Filter file
Add code the file app/Filters/AuthGuard.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?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('/login'); } } public function after(RequestInterface $request, ResponseInterface $response, $arguments = null) { } } ?> |
Step 6: Update Filter file
Add code the file app/Config/Filters.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php public $aliases = [ 'csrf' => CSRF::class, 'toolbar' => DebugToolbar::class, 'honeypot' => Honeypot::class, 'invalidchars' => InvalidChars::class, 'secureheaders' => SecureHeaders::class, // add custom 'authGuard' => \App\Filters\AuthGuard::class, ]; ?> |
Step 7: Update routes file
Add/Update code the file app/Config/Routes.php in your CodeIgniter installation with you controller’s name.
1 2 3 4 5 6 7 |
<?php // custom create routes $routes->get('/', 'User::index'); $routes->get('/register', 'User::index'); $routes->get('/login', 'user::login'); $routes->get('/dashboard', 'User::dashboard', ['filter' => 'authGuard']); ?> |
Step 8: Create and Update User Model
Create a model file named UserModel.php inside “app/Models” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?php /** * Description of Users Model * * @author Team TechArise * * @email info@techarise.com */ namespace App\Models; use CodeIgniter\Model; class UserModel extends Model { protected $table = 'users'; protected $allowedFields = [ 'user_name', 'name', 'email', 'password', 'created_date', 'status' ]; } ?> |
Step 9: Create controllers
Create a controllers file named User.php inside “app/Controllers” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
<?php /** * Description of Users Controller * * @author Team TechArise * * @email info@techarise.com */ namespace App\Controllers; use App\Models\UserModel; class User extends BaseController { public function index() { $data = array(); helper(['form']); return view('user/register', $data); } // public function register() { helper(['form']); $rules = [ 'user_name' => 'required|min_length[2]|max_length[50]', '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'), 'user_name' => $this->request->getVar('user_name'), 'email' => $this->request->getVar('email'), 'password' => password_hash($this->request->getVar('password'), PASSWORD_DEFAULT), 'created_date' => time(), 'status' => 1, ]; $userModel->save($data); return redirect()->to('/login'); } else { $data['validation'] = $this->validator; return view('user/register', $data); } } // login form public function login() { $data = array(); helper(['form']); return view('user/login', $data); } // check login auth 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 = [ 'user_id' => $data['user_id'], 'name' => $data['name'], 'user_name' => $data['user_name'], 'email' => $data['email'], 'isLoggedIn' => TRUE ]; $session->set($ses_data); return redirect()->to('/dashboard'); } else { $session->setFlashdata('msg', 'Password is incorrect.'); return redirect()->to('/login'); } } else { $session->setFlashdata('msg', 'Email does not exist.'); return redirect()->to('/login'); } } // dashboard public function dashboard() { $data = array(); $data['session'] = session(); return view('user/dashboard', $data); } public function logout() { $session = session(); $session->destroy(); return redirect()->to('/login'); } } ?> |
Step 10: Create views
Create a views file named register.php inside “add/Views/user” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?php echo view('templates/header'); ?> <main class="flex-shrink-0"> <div class="container mt-5"> <div class="row justify-content-md-center"> <div class="col-5"> <h2 class="mt-5 text-center">Register User</h2> <p> </p> <?php if (isset($validation)) : ?> <div class="alert alert-warning"> <?= $validation->listErrors() ?> </div> <?php endif; ?> <form action="<?php echo base_url(); ?>/user/register" method="post"> <div class="form-group mb-3"> <input type="text" name="user_name" placeholder="User Name" value="<?= set_value('user_name') ?>" class="form-control"> </div> <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> </main> <?php echo view('templates/footer'); ?> |
Step 11: Create views
Create a views file named login.php inside “add/Views/user” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php echo view('templates/header'); ?> <main class="flex-shrink-0"> <div class="container mt-5"> <div class="row justify-content-md-center"> <div class="col-5"> <p> </p> <?php if (session()->getFlashdata('msg')) : ?> <div class="alert alert-warning"> <?= session()->getFlashdata('msg') ?> </div> <?php endif; ?> <form action="<?php echo base_url(); ?>/user/loginAuth" method="post" class="form-signin"> <h2 class="text-center">Login in</h2> <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> </main> <?php echo view('templates/footer'); ?> |
Step 12: Create views
Create a views file named dashboard.php inside “add/Views/user” folder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php echo view('templates/header'); ?> <main class="flex-shrink-0"> <div class="container"> <div class="row justify-content-md-center"> <div class="wrapper thank-you-page"> <div class="thank-you-pop"> <img src="<?php echo HTTP_IMAGES_PATH; ?>tick.png" alt=""> <h1>Dashboard</h1> <h3 class="cupon-pop">Welcome: <span> <?php if (!empty($session)) { print $session->get('name'); } else { print "User"; } ?> </span> </h3> </div> <hr> </div> </div> </div> </div> </main> <?php echo view('templates/footer'); ?> |
Create files named (header.php, menus.php and footer.php)
This file contains the header and footer section of the webpage. The Bootstrap library is used to provide a better UI, so, include it in the header and footer section.
i) header.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!doctype html> <html lang="en"> <head> <meta name="google-site-verification" content="jlByZLO42gqjZgfAEj29-VYfJC2hEwUj1KSeQpiGJcI" /> <link rel="canonical" href="https://techarise.com/" /> <meta name="author" content="TechArise"> <meta name="description" content="Learn Web Development Tutorials & Web Developer Resources, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, with TechArise tutorials. View live demo"> <meta name="keywords" content="TechArise, tutorial TechArise, tutorials, freebies, resources, web development, webdev, demo, PHP, MySQL, jQuery, CSS, XHTML, jQuery UI, CSS3, HTML5, HTML, web design, webdesign, php script, dynamic web content" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="icon" type="image/ico" href="https://techarise.com/wp-content/themes/v1/favicon.ico"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <!--- Custom css ---> <link href="<?php print HTTP_CSS_PATH; ?>sticky-footer-navbar.css" rel="stylesheet"> <link href="<?php print HTTP_CSS_PATH; ?>style.css" rel="stylesheet"> <title>Create Registration Form with CodeIgniter | Tech Arise</title> </head> <body> <?php echo view('templates/menus'); ?> |
ii) menus.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<header> <!-- Fixed navbar --> <nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark"> <div class="container-fluid"> <a class="navbar-brand" href="https://techarise.com">TechArise</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav me-auto mb-2 mb-md-0"> <li class="nav-item"> <a class="nav-link active" aria-current="page" href="https://techarise.com">Home</a> </li> </ul> <form class="d-flex"> <?php if (!empty(session())) { ?> <a class="btn btn-outline-primary" href="<?php echo base_url(); ?>/user/logout">Logout</a> <?php } else { ?> <a class="btn btn-outline-primary" href="<?php echo base_url(); ?>/register">Login <?php print_r(session()->get('name')); ?> </a> <?php } ?> </form> </div> </div> </nav> </header> |
iii) footer.php
1 2 3 4 5 6 7 8 |
<footer class="footer"> <div class="container"> </div> </footer> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script> </body> </html> |