How to create a Login and Logout System in CodeIgniter with validation?
In my previous articles, I have explained much about CodeIgniter. This is sufficient for you guys to start working on a project. As I follow learn with codes approach. Let’s start learning – how to create login and logout System in CodeIgniter with form validation?
To create a login and logout system, we need to follow a few simple steps. Following are the steps to create a login and logout system in CodeIgniter with validation. Additionally, I will be providing descriptions of the steps and codes where needed.
Steps to create login System in CodeIgniter with form validation
Note: We need to mention below the line of codes in the starting of each file so I will not mention this every time.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
Step #1: Create Login controller to show the login page
Create a class file in the CodeIgniter’s application/controllers folder with name Login.php. Now add the line of codes given below in that file and save.
class Login extends CI_Controller {
public function index() {
$this->template->view('login');
}
}
- Create Pagination In PHP And MySQL – Complete Code
- MySQL UNION Operator And Comparison To UNION ALL
- MySQL CASE In WHERE CLAUSE: Conditional Conditions
Step #2: Create a login view for login form
The controller above will show the template login.php. Create a template file with the name login.php in CodeIgniter’s application/views folder. This file will display the user login form. This should have two fields, i.e. for username and password.
Below is the code for creating a simple login page HTML. This page also contains some styling. However, this is not required. But if you are going for any web page development, styles must be used. This will make the pages user-friendly. Below is the HTML, copy this to application/views/login.php.
Login view page code (views/ login.php)
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Login System Demo | techbriefers.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{font-family:Arial,Helvetica,sans-serif}
input[type=password],input[type=text]{width:100%;padding:12px 20px;margin:8px 0;display:inline-block;border:1px solid #ccc;box-sizing:border-box}
button{background-color:#4caf50;color:#fff;padding:14px 20px;margin:8px 0;border:none;cursor:pointer;width:45%}
button:hover{opacity:.8}
.cancelbtn{background-color:#f44336;margin:auto;padding:16px}span.psw{float:right;padding-top:16px}
@media screen and (max-width:300px){
span.psw{display:block;float:none}
button{width:100%}
.container{width:100%}
}
@media screen and (max-width:500px) and (min-width:301px){
span.psw{display:block;float:none}
button{width:100%}
.container{width:80%}
}
p.alert{width:100%;background:#4b99ec;padding:10px;color:#fff;text-align:left}
p.success{background:#0a8e15}
p.error{background:#e81d1d}
</style>
</head>
<body>
<form action="<?php echo base_url('login/auth') ?>" method="post">
<div class="container">
<h2>Login Form</h2>
<?php if ($this->session->flashdata('alert')): ?>
<p class="alert <?php echo $this->session->flashdata('alert')['type']; ?>"><?php echo $this->session->flashdata('alert')['msg']; ?></p>
<?php endif; ?>
<label for="uname"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="uname" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<div style="text-align: center;">
<button type="reset" class="cancelbtn">Cancel</button>
<button type="submit">Login</button>
</div>
</div>
</form>
</body>
</html>
To authorize a user making attempt to log-in, we will need a few things.
- A database where users’ data will be stored
- A model which will interact with that data
- A controller to perform authorization logic
To create authorization code, we need to match the user entered data with our data. For this, we need to have a database to store the user’s credentials. I am creating a simple database in MySQL. The table name which will store user’s data is ‘my_users’. I am keeping the table structure very simple. It contains only four columns. First is user_id, which is the auto-incremented primary key of integer type. Other three columns, user_uname, user_full_name, and user_password are of VARCHAR types of length 100.
Below is the query to create the table I created. Create a database for Users
--
-- Table structure for table `my_users`
--
CREATE TABLE `my_users` (
`user_id` int(11) NOT NULL,
`user_uname` varchar(100) NOT NULL,
`user_full_name` varchar(100) NOT NULL,
`user_password` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Insert User’s data to create a user in the database
Below I am mentioning the query to insert the data for two users. First is ‘John Williams’ with username ‘john123’ and password ‘123john’. The other is ‘Davis Wilson’ with username ‘davis2020’ and password ‘2020davis’.
INSERT INTO `my_users` (`user_id`, `user_uname`, `user_full_name`, `user_password`) VALUES (NULL, 'john123', 'John Williams', '123john'), (NULL, 'davis2020', 'Davis Wilson', '2020davis');
Creating Model code for fetching Users’ details
In CodeIgniter, Models are responsible to interact directly to the database. All the codes related to the database are written in model files. To make user login authorization in CodeIgniter, I will create a model with the name LoginModel. This login model will contain the methods to fetch data from my_users table. This model will be saved in the application/model folder with filename LoginModel.php. Let’s have a look at the model code, afterward, I will explain the code.
class LoginModel extends CI_model {
public function fetchUserDetails($user_name) {
$this->db->select('user_id, user_full_name, user_password');
$this->db->from('my_users');
$this->db->where('user_uname', $user_name);
$query = $this->db->get();
return $query->result_array();
}
}
Model code Explanation
In the code block above, I have created a class with the name LoginModel which extend CI_model. This is how we will create a model in CodeIgniter. Inside this class, I have created a method named fetchUserDetails() which takes an argument, i.e. username. Then, to create query, select() method is used to set columns to fetch. Then from() method is used to set table name from which data will be fetched. After that, where() method is used to apply condition to match column ‘user_uname‘ with value $user_name. This will make a query which will be equal to the below query written in simple SQL language and PHP.
SELECT user_id, user_full_name, user_password FROM my_users WHERE user_uname = $user_name;
$query = $this->db->get(); will get the query object and by using $query->result_array(); we will get the fetched results in array form.
This was all we need to do for fetching user’s data from the database. Now, let’s move towards the controller to write logic codes for validation and authorization.
CodeIgniter login form validation code
Validating a form is a way better than directly authorizing the user. It will protect our database to get fewer hits as it will pass basic validations prior to database access. So I will create a form validation code in the controller. After the validation will pass, the authorization will take place.
For form validations in CodeIgniter, we need to load the form_validation library.
$this->load->library('form_validation');
After loading the form validation library, we need to set validation rules for all the entities that we want to validate. Here, I will set both the values to be required only.
$this->form_validation->set_rules('uname', 'Username', 'required');
$this->form_validation->set_rules('psw', 'Password', 'required');
To run these validation rules, use run() method of this form_validation library.
If $this->form_validation->run() will return true, then we can proceed to authorization code.
- How to remove index.php from CodeIgniter URL in steps?
- How to create a new CodeIgniter project
- CodeIgniter Directory Structure explanation
Full login controller code (controller/Login.php)
class Login extends CI_Controller {
public function index() {
$this->load->view('login');
}
public function auth() {
$this->load->library('form_validation');
$redirect_to = 'login';
$this->form_validation->set_rules('uname', 'Username', 'required');
$this->form_validation->set_rules('psw', 'Password', 'required');
if ($this->form_validation->run() == true) {
$username = $this->input->post('uname');
$password = $this->input->post('psw');
$this->load->model('LoginModel');
$user_details = $this->LoginModel->fetchUserDetails($username);
if (!empty($user_details)) {
if ($password != $user_details[0]['user_password']) {
$this->session->set_flashdata('alert', array('type' => 'error', 'msg' => '*Invalid Username/Password'));
} else {
$user_data = array('id' => $user_details[0]['user_id'], 'name' => $user_details[0]['user_full_name']);
$this->session->set_userdata($user_data);
$this->session->set_flashdata('alert', array('type' => 'success', 'msg' => 'Hi ' . $user_details[0]['user_full_name'] . '!'));
$redirect_to = 'dashboard';
}
} else {
$this->session->set_flashdata('alert', array('type' => 'error', 'msg' => '*User Not Found.'));
}
}
return redirect($redirect_to);
}
}
Code Explanation:
If form validation returns true, that means the form values validation is successful.
Let’s first assign the form posted values to variables.
$username = $this->input->post('uname');
$password = $this->input->post('psw');
After this Load login model where we have written code to interact database. The Login model has fetchUserDetails() method which fetched user’s details matching with the username entered. We will pass Username as a parameter to this method. The results returned by from fetchUserDetails() method are assigned to a variable $user_details.
Then testing if the returned value has some details, and then this means that there exist data for that username. Otherwise, it will throw an error message saying “User Not Found”. After getting details, we will match the password from the database to the one user entered. If the passwords will match, the user will be logged in. For the logged-in user, some session values are to be set. The vales are id that is the user’s ID and name that is User’s name. The user will be redirected to dashboard with a message “ ‘Hi ‘ . $user_details[0][‘user_full_name’] . ‘!’”. If passwords will not match, it will throw an error saying “Invalid Username/Password”. Wherever error will trigger, the user will be redirected back to the login page.
After Successful login, User will see the dashboard. There I have created a link to logout. This will take the user to the logout controller where all the user data (session) will be cleared. And User will be redirected back to the login page.
I also have added a validation that logged in user should not access the login page. It will automatically redirect to the dashboard. Whereas, not logged in user will not be able to see dashboard. There it will force the user to login first.
Dashboard controller code (controller/Dashboard.php)
class Dashboard extends CI_Controller {
public function index() {
if (empty($this->session->userdata('id'))) {
$this->session->set_flashdata('alert', array('error' => 'Please login.'));
redirect(base_url('login'));
}
$this->load->view('dashboard');
}
}
Dashboard view page code (views/dashboard.php)
<!DOCTYPE html>
<html>
<head>
<title>Codeigniter Login System Demo Dashbard | techbriefers.com</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body{font-family:Arial,Helvetica,sans-serif}
.container{width:40%;margin:auto;padding:16px;text-align:center}
/* Change styles for span and cancel button on extra small screens */
@media screen and (max-width: 300px) {
.container{width: 100%;}
}
@media screen and (max-width: 500px) and (min-width: 301px){
.container{width: 80%;}
}
p.alert{width:100%;background:#4b99ec;padding:10px;color:#fff;text-align:left}
p.success{background:#0a8e15}
p.error{background:#e81d1d}
</style>
</head>
<body>
<div class="container">
<?php if ($this->session->flashdata('alert')): ?>
<p class="alert <?php echo $this->session->flashdata('alert')['type']; ?>"><?php echo $this->session->flashdata('alert')['msg']; ?></p>
<?php endif; ?>
<h2>Dashboard</h2>
<h3>Hello <?php echo $this->session->userdata('name'); ?>!</h3>
<h5>You are logged in. Welcome to dashboard!</h5>
<div style="text-align: center;">
<a href="<?php echo base_url('logout'); ?>">Logout</a>
</div>
</div>
</body>
</html>
- How To Search Child Element In A Div Or Any Element By JQuery Has()
- What Is An IDE (Integrated Development Environment)
- How To Read All Files And Directories In A Folder | PHP Glob()
Logout System code in Codeigniter (controller/Logout.php)
class Logout extends CI_Controller {
public function index() {
$this->session->unset_userdata(array('id', 'name'));
$this->session->set_flashdata('alert', array('type' => 'info', 'msg' => 'You are logged out.'));
redirect(base_url('login'));
}
}
I like this internet site because so much utile material on here :D.
Thank you
Excellent blog post. I absolutely love this site. Keep it up!
Aw, this was an incredibly nice post. Finding the time and actual
effort to produce a superb article… but what can I say… I procrastinate a lot and never manage to get anything done.
Hurrah, that’s what I was searching for, what a information! present here at this web
site, thanks admin of this site.