Making a Multi – level Login System in CodeIgniter

CodeIgniter is becoming very popular due to its reliability and ability to make an application . Moreover with CodeIgniter development of an application to be easy . Included is create a login system which is an essential element of an application . This tutorial explains how to create a login system using CodeIgniter and make multilevel login with CodeIgniter . Hopefully Helpful .

1 . Know the Library Session, Form Validation And Database

The most important libraries in the login process is SESSION . Actually PHP already provides a function to perform SESSION, Database and Form Validation process , but the Framework has been ” wrapped ” become easier to use and a lot of features that we can use . At CodeIgniter Framework there is also a library that can properly manage the Session SESSION Class, Form Validation Class and Manage Database database Class . With this Classes you will be facilitated in managing SESSION, Database and Form Validation of users accessing your application . In the user guide / documentation of CodeIgniter already explained very clearly in the Session, Form Validation And Database Class . To view or you can simply call the Session and Database Class From Your CodeIgniter Project/Application/config/autoload.php in line number 55 .


$autoload['libraries'] = array("database","session","form_validation");

Yes, the above is a way to call Session Class that we will need later. Now you must set session encryption Key in CodeIgniter Project/Application/config/config.php in line number 227 .

 $config['encryption_key'] = '!@#$%^&*';
 

And Also You Can Set your Database information in CodeIgniter Project/Application/config/database.php in line number 51 – 65 .

Session that we have set will do the “maintenance” of the user who is using the session. And it is certainly the session expiry now got in CodeIgniter already has features to set the age of the session. How??? you simply open the config.php file. If you do not know me you know you get to the directory Your CodeIgniter Project/application /config / config.php.

Then find the line 247 you will see the setting session there. However, I will not describe in detail, you can access to get more complete documentation on setting session. Yes on line 248 no session expiration settings, with the default size of the second session can be stale in CodeIgniter for 2 hours or 7200 seconds. You can do all the settings as they pleased origin converted to seconds. And if you give the number 0 (zero / zero) then the session will never stale alias expired. To check session we can use:


if(!$this->session->userdata('username'))

{

redirect('admin/login');

}

else

{

redirect('admin/home');

}

Okay the above code snippet is how we are going to check , whether the session is already in use or not . If no alias is not activated by the user or used by the user application ( marked with ! Exclamation point ) then will be directed to login page . And vice versa will be directed to the home page . Less like that later on the workings of belonging CodeIgniter Session library . We’ll start by creating a login system and the second is to create a multi-level login system alias each level can be adjusted to the level of the login user user alias .

2 . Creating System Login

The following will be discussed on how to create a login system using CodeIgniter . Okay lah we go directly to the scene …

2.1 . Creating a Table

We begin by making the first table , this table serves to hold user data will we use in our practice to make the system login . Immediately, you create the database , making use phpMyAdmin , SQLyog or any application was yes . Create a database with the name db_login example , the following query :

 CREATE DATABASE db_login;
 

If you have created the database, create a table as follows:


CREATE TABLE `user` (

`username` VARCHAR( 50 ) NOT NULL , `password` VARCHAR( 32 ) NOT NULL , `name` VARCHAR( 100 ) NULL , `level` INT( 1 ) NOT NULL , `status` INT( 1 ) NOT NULL , PRIMARY KEY ( `username` )

) ENGINE = MYISAM ;

And enter / insert the data that we will use the following query:


INSERT INTO user VALUES ('Omran', MD5( '123456' ) , 'Omran Jamal', '1', '1');

INSERT INTO user VALUES ('Eshaan', MD5( '654321' ) ,'Eshaan Ahmed Foysal', '2', '1');

Make Model

Next create a new file, you name m_login.php example, here is a snippet of code from script m_login.php:

 <?php
if(!defined('BASEPATH')) exit('Hacking Attempt : Get Out of the system ..!');

class M_login extends CI_Model

{

public function __construct()

{

parent::__construct();

}

public function takeUser($username, $password, $status)

{

$this->db->select('*');

$this->db->from('user');

$this->db->where('username', $username);

$this->db->where('password', $password);

$this->db->where('status', $status);

$query = $this->db->get();

return $query->num_rows();

}

public function userData($username)

{

$this->db->select('username');

$this->db->select('name');

$this->db->where('username', $username);

$query = $this->db->get('user');

return $query->row();

}

}

Making View to Login

If you’ve made the next step is the model we will create a file view, whose function is to display the login form. Create a new file again, you just love the name eg form_login.php. Like this script:

 <html>

<head>

<title>Form Login</title>

<style>

body

{

font-family:Calibri;

margin:50px;

}

#form-login{

margin:auto;

width:500px;

padding:10px;

border:1px #ccc solid;

font-size:18px;

font-weight:bold;

color:#FF6600;

}

.inputan

{

padding:3px;

font-family:Calibri;

border:1px solid #ccc;

}

.tombol

{

padding:5px;

background:#FF6600;

color:#FFF;

font-weight:bold;

font-family:Calibri;

font-size:15px;

border:#eee 1px solid;

}

.error

{

color:#FF6600;

font-size:11px;

}

</style>

</head>

<body>

<form action="<?php echo base_url();?>index.php/login/login_form" method="post" name="login">

<div id="form-login">

Administrator Page - Plase Login First

<br><br>

<table border="0" cellpadding="4">

<tr>

<td>Username</td>

<td>:</td>

<td><input type="text" size="40" name="username" value="<?php echo set_value('username');?>"> <?php echo form_error('username');?></td>

</tr>

<tr>

<td>Password</td>

<td>:</td>

<td><input type="password" size="40" name="username" value="<?php echo set_value('password');?>"> <?php echo form_error('password');?></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

<td><input type="submit" name="login" value="Login"> </td>

</tr>

</table>

</div>

</form>

</body>

</html>

Creating Controller

How long really do, ga worry. Let’s continue by creating a new file for the controller, with name login.php example, the following script:


<?php
if(!defined('BASEPATH')) exit('Hacking Attempt : Get Out of the system ..!');

class Login extends CI_Controller

{

public function __construct()

{

parent::__construct();

$this->load->model('m_login');

$this->load->helper('url');

}

public function index()

{

$session = $this->session->userdata('isLogin');

if($session == FALSE)

{

redirect('login/login_form');

}else

{

redirect('home');

}

}

public function login_form()

{

$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean');

$this->form_validation->set_rules('password', 'Password', 'required|md5|xss_clean');

$this->form_validation->set_error_delimiters('<span class="error">', '</span>');

if($this->form_validation->run()==FALSE)

{

$this->load->view('form_login');

}else

{

$username = $this->input->post('username');

$password = $this->input->post('password');

$cek = $this->m_login->takeUser($username, $password, 1);

if($cek <> 0)

{

$this->session->set_userdata('isLogin', TRUE);

$this->session->set_userdata('username',$username);

redirect('home');

}else

{

?>

<script>

alert('Failed Login: Check your username and password!');

history.go(-1);

</script>

<?php

}

}

}

public function logout()

{

$this->session->sess_destroy();

redirect('login/login_form');

}

}

?>

Running a login system

How is the spirit? Wait, I have prepared in an attachment with this Tutorial. Okay now please try it in the browser, if it is true you will be taken to the page as shown in the following figure:

CodeIgniter Login System with Multilevel

And create a new file with the name home.php, what does it do? Please check back on login.php was a line of code to redirect directly to the controller by the name of home. Well, the script writes home as follows:


 <?php

if(!defined('BASEPATH')) exit('Hacking Attempt. Keluar dari sistem.');

class Home extends CI_Controller

{

public function __construct()

{

parent::__construct();

$this->load->library(array('session'));

}

public function index()

{

if($this->session->userdata('isLogin') == TRUE)

{

redirect('login/login_form');

}else

{

$this->load->view('home_v');

}

}

}

 

And create another file home.php in your views folder,


<html>

<head>

<title>Administration</title>

<style>

body

{

font-family:Calibri;

}

</style>

</head>

<body>

<h2>Hi, Welcome Administrator</h2>

</body>

</html>

Try the browser, if what you make right. Then you will get the following display:

Login home

3. Creating Multilevel Login

 

Once we make a how to make a login system with CodeIgniter, this time we will move to a more complex system than the system log, namely Multi-level login. Okay we start with preparation beforehand.

3.1. Getting Started

Yes, preparation is that we shall devise in advance what we will create later in the system log. We will create a design that is suppose we have two levels of login, the Admin and Operator. Where if one login then will be directed to a specific page. How have understood his right design?

3.2. Creating Login

Login page you created in the previous discussion, we’ll just add a combobox aimed at user level. Modifiy form_login.php file with the following script:

So the login screen should appear as follows:


<form action="<?php echo base_url();?>index.php/login/login_form" method="post" name="login">

<div id="form-login">

Administrator Page - Plase Login First

<br><br>

<table border="0" cellpadding="4">

<tr>

<td>Username</td>

<td>:</td>

<td><input type="text" size="40" name="username" value="<?php echo set_value('username');?>" class="inputan"> <?php echo form_error('username');?></td>

</tr>

<tr>

<td>Password</td>

<td>:</td>

<td><input type="password" size="40" name="password" value="<?php echo set_value('password');?>"> <?php echo form_error('password');?></td>

</tr>

<tr>

<td>Level</td>

<td>:</td>

<td><select name="level" class="inputan">

<option value="1">Admin</option>

<option value="2">Operator</option>

</select></td>

</tr>

<tr>

<td>&nbsp;</td>

<td>&nbsp;</td>

<td><input type="submit" name="login" value="Login"> </td>

</tr>

</table>

</div>

</form>

So the login screen should appear as follows:

Login Level

3.3. Modifications to the model file m_login.php

Model modification is necessary because we will match the username and password in accordance with the level. Just change the following line:


<?php

if(!defined('BASEPATH')) exit('Hacking Attempt : Get Out of the system ..!');

class M_login extends CI_Model

{

public function __construct()

{

parent::__construct();

}

public function takeUser($username, $password, $status, $level)

{

$this->db->select('*');

$this->db->from('user');

$this->db->where('username', $username);

$this->db->where('password', $password);

$this->db->where('status', $status);

$this->db->where('level', $level);

$query = $this->db->get();

return $query->num_rows();

}

public function userData($username)

{

$this->db->select('username');

$this->db->select('name');

$this->db->where('username', $username);

$query = $this->db->get('user');

return $query->row();

}

}

3.4. Modifications Controller login.php file

Next do mofikasi the login controller. Here we will add a session to the level. And later on this level is the reference to distinguish among users.


<?php
if(!defined('BASEPATH')) exit('Hacking Attempt : Keluar dari sistem..!!');

class Login extends CI_Controller

{

public function __construct()

{

parent::__construct();

$this->load->model('m_login');

$this->load->library(array('form_validation','session'));

$this->load->database();

$this->load->helper('url');

}

public function index()

{

$session = $this->session->userdata('isLogin');

if($session == FALSE)

{

redirect('login/login_form');

}else

{

redirect('home');

}

}

public function login_form()

{

$this->form_validation->set_rules('username', 'Username', 'required|trim|xss_clean');

$this->form_validation->set_rules('password', 'Password', 'required|md5|xss_clean');

$this->form_validation->set_error_delimiters('<span class="error">', '</span>');

if($this->form_validation->run()==FALSE)

{

$this->load->view('form_login');

}else

{

$username = $this->input->post('username');

$password = $this->input->post('password');

$level = $this->input->post('level');

$cek = $this->m_login->takeUser($username, $password, 1, $level);

if($cek <> 0)

{

$this->session->set_userdata('isLogin', TRUE);

$this->session->set_userdata('username',$username);

$this->session->set_userdata('level',$level);

redirect('home');

}else

{

echo " <script>

alert('Failed Login: Check your username and password!');

history.go(-1);

</script>";

}

}

}

public function logout()

{

$this->session->sess_destroy();

redirect('login/login_form');

}

}

?>

Okay already see the change? yes for those who have not met, try to see in this line

 $level = $this->input->post('level');
 

and


$this->session->set_userdata($level);
 

yes that’s the addition of a new script as a “weapon” to create multilevel login.

3.5. Changing the Home page (Controller and View)

Change the controller home.php file into:


<?php
if(!defined('BASEPATH')) exit('Hacking Attempt: Get out of the system ..!');

class Home extends CI_Controller

{

public function __construct()

{

parent::__construct();

$this->load->helper('url');

$this->load->model('m_login');

}

public function index()

{

if($this->session->userdata('isLogin') == FALSE)

{

redirect('login/login_form');

}else

{

$this->load->model('m_login');

$user = $this->session->userdata('username');

$data['level'] = $this->session->userdata('level');

$data['user'] = $this->m_login->userData($user);

$this->load->view('home', $data);

}

}

}

?>

Now Modify the file home.php in your views. Here we will change the display according to the level of the user.


<html>

<head>

<title>Administration</title>

<style>

body

{

font-family:Calibri;

}

</style>

</head>

<body>

<?php

if($level == "1")

{

?>

<h2>Hi <?php echo $user->name;?>, Welcome to Login you as a Administrator <?php echo anchor('login/logout', 'Logout');?></h2>

<?php

}else

{

?>

<h2>Hi <?php echo $user->name;?>, Welcome to Login you as a Operator <?php echo anchor('login/logout', 'Logout');?></h2>

<?php

}

?></body>

</html>

And Now test on your browser, here is a view from the home page:

Administration LoginFigure 1. Home page of the Admin level 

operator LoginFigure 2. Home page level Operator

Okay the point is that we can distinguish the user level by setting the session that you created earlier. So, you can make modifications through the level that we set through the Controller. Multi-level and make you make far better meet the needs of your application.

Download

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCE PHP 5.3 Certification and professional web development course at IBCS-PRIMAX Software (Bangladesh) Limited – a leading Training Institute in the country.
Print Friendly
14 comments on “Making a Multi – level Login System in CodeIgniter
  1. Hi,
    Nice job. Really love this source code. For some reason I cannot log in even after creating a user and password.
    I keep getting the same error message from Localhost. Please help me

  2. Hi. Thank you for your tutorial. It is of great help to me. Whoever, i have a problem with the first login script. it cant log in. It instead transfers my password to the username field and and provides an error message at the password field. Can you help please.

  3. i copied the code exactly using username as Omran and password as 123456 but it seems as The Password field is required..

Leave a Reply

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