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.

1

2

<?php

defined('BASEPATH')ORexit('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.

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.

Step #3: Create an authorization code for the login system in CodeIgniter

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

1

2

3

4

5

6

7

8

9

10

--

--Table structure fortable`my_users`

--

CREATE TABLE`my_users`(

`user_id`int(11)NOTNULL,

`user_uname`varchar(100)NOTNULL,

`user_full_name`varchar(100)NOTNULL,

`user_password`varchar(100)NOTNULL

)ENGINE=InnoDB DEFAULTCHARSET=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’.

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.

1

2

3

4

5

6

7

8

9

classLoginModelextendsCI_model{

publicfunctionfetchUserDetails($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.

1

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.

1

$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.

1

2

$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.

$this->session->set_flashdata('alert',array('type'=>'error','msg'=>'*User Not Found.'));

}

}

returnredirect($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.

1

2

$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.