If you are also learning CodeIgniter right now then you are on the right place today. Let's learn how we can create an authentication system in CodeIgniter 4. This is the latest version of CodeIgnite...
Gurpreet Kait
Author
If you are also learning CodeIgniter right now then you are on the right place today. Let's learn how we can create an authentication system in CodeIgniter 4. This is the latest version of CodeIgniter in which we are going to build login and register functionality in CodeIgniter.
CodeIgniter is a very basic framework as compare to Laravel. Because it won't take much time to understand it. Let's move on tutorial now.
First thing that you have to do is to install the CodeIgniter because without that you can't move forward. Use below command to install the 4 version of CodeIgniter. This is the latest version which I am using now. If you are working on any other version please do take a look at documentation first.
Now, Let's assume we have installed our project successfully and now we have to create three pages.
login page
Register page
Dashboard page
Because these are the most important pages. Let me explain, First of all you will land of Login page to login and if not have credentials then you will register after register you will login and land on dashboard. So, this is the flow. Let's learn how we can make it more better.
After doing this we will be able to create login and register in CodeIgniter successfully
In App directory we do have View directory in which we will create these files.
login page code
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metahttp-equiv="X-UA-Compatible"content="IE=edge"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>login</title><linkrel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"></head><body><divclass="container"><divclass="row d-flex align-items-center justify-content-center"style="min-height: 600px;"><divclass="card"><divclass="card-content"><divclass="card-body shadow"><?phpif (isset($_SESSION)) { ?><divclass="alert alert-success"role="alert"><?phpecho$_SESSION;
unset($_SESSION);
?></div><?php } ?><divclass="card-title">Login</div><formaction="login/auth"method="POST" ><divclass="form-group"><inputtype="email"placeholder="enter email.."class="form-control"name="email"required></div><divclass="form-group"><inputtype="password"placeholder="enter password.."class="form-control"name="password"required></div><divclass="form-group"><buttonclass="btn btn-secondary shadow-sm">Login</button><ahref="register">Do not have any account</a></div></form></div></div></div></div></div></body></html>
We will create login page first it look like as in the picture below.
Now, we will create register page where a use can register and after that we will move to code functionality in which we will cover all the stuff related to model, view, controller etc..
Almost in each framework these process follows. I mean each framework does have MVC structure. Model , View and Controller. In Model we do all the stuff related to getting data from database and interacting with the tables. Basically Model represents tables for each table. We do have separate Model. In the same way we do have View directory which means frontend. Basically in View we do store our html and the files that will be viewed on frontend. In Controller we all logic kind of stuff. For example getting data from model and playing with that data and transferring to view.
This is all about MVC. With the same flow we will build login and register in CodeIgniter
Establish Database Connection
Without database we are not able to do anything with Authentication. So, I have decided do it first. For this, we have to go to Config directory and in this we will have Database file in which you have put some database information and also have to create the database.
We are going to make migration because If you are using a framework and creating tables manually in database then this is not a good practice. let's use migration for more consistency.
When you will run the command to create the model you will have everything. But don't forget to add the usable fields in $allowedFields. I have only created two functions first to register the user and second for check the user login details.
Create Controller File
Now, we have to create the controller to make some logics related to login and register functionality. We do have Controller directory in App directory. Create a controller via command , take enjoy of CLI also, don't go very straight forward.
php spark make:controller AuthController
Edit AuthController File
Add some code to AuthController file to do all the logics for login and register. I'll explain code below don't forget to read.
If you are familiar with OOP then you might know about construct if not then read about Construct
Index is default method, when you do not mention any method in front of controller in your route file then index will get called.
Login method basically called to target the view page and in condition we are checking if use logged in or not so that he cannot jump to login page again.
Logout method for unset the session and logout the user.
Register method is used for the same purpose to call the view file.
doLogin method for login logic.
doRegister method for Register logic.
Edit Route File
If you don't know about the routing take a look at documentation then it would be easy for you to build login and register in CodeIgniter. Otherwise let me explain you. Routing is basically represent the all routes of a website in any framework. We do keep our pages URL in routing file. It does have some security like for "post" route we can specify post and for get route we can specify get in front of URL.
See in the code below.
<?phpnamespaceConfig;
// Create a new instance of our RouteCollection class.$routes = Services::routes();
// Load the system's routing file first, so that the app and ENVIRONMENT// can override as needed.if (is_file(SYSTEMPATH . 'Config/Routes.php')) {
require SYSTEMPATH . 'Config/Routes.php';
}
/*
* --------------------------------------------------------------------
* Router Setup
* --------------------------------------------------------------------
*/$routes->setDefaultNamespace('App\Controllers');
$routes->setDefaultController('Home');
$routes->setDefaultMethod('index');
$routes->setTranslateURIDashes(false);
$routes->set404Override();
// The Auto Routing (Legacy) is very dangerous. It is easy to create vulnerable apps// where controller filters or CSRF protection are bypassed.// If you don't want to define all routes, please use the Auto Routing (Improved).// Set `$autoRoutesImproved` to true in `app/Config/Feature.php` and set the following to true.// $routes->setAutoRoute(false);/*
* --------------------------------------------------------------------
* Route Definitions
* --------------------------------------------------------------------
*/// We get a performance increase by specifying the default// route since we don't have to scan directories.$routes->get('/', 'AuthController::index');
$routes->get('/login', 'AuthController::login');
$routes->post('/login/auth', 'AuthController::doLogin');
$routes->get('/logout', 'AuthController::logout');
$routes->get('/register', 'AuthController::register');
$routes->get('/dashboard', 'AuthController::dashboard');
$routes->post('/register/auth', 'AuthController::doRegister');
/*
* --------------------------------------------------------------------
* Additional Routing
* --------------------------------------------------------------------
*
* There will often be times that you need additional routing and you
* need it to be able to override any defaults in this file. Environment
* based routes is one such time. require() additional route files here
* to make that happen.
*
* You will have access to the $routes object within that file without
* needing to reload it.
*/if (is_file(APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php')) {
require APPPATH . 'Config/' . ENVIRONMENT . '/Routes.php';
}
Now, you are ready to go and can use this code too. Don't forget to understand the code before copy.
Conclusion
Our Authentication system is ready in CodeIgniter 4. Basically I do work with Laravel mostly because of a company's project I moved to CodeIgniter. I learned it, I decided to share it with you.
If you can add something into this please do comment below. I'll add your changes too.