Want to learn coding through videos for free?
Check my youtube channel => HERE!

How to make multi level user login using codeigniter [Complete Tutorial]

How to make multi level user login using codeigniter [Complete Tutorial]

I think you will agree if I say:

“It is very HARD to create multi level user login using Codeigniter.”

Good news:

Well, it turns out. You can easily create multi level user login using Codeigniter right now.!

Today, In this tutorial, I will share with you how to create multi level user login using codeigniter.

Step by step.

Not only that, I will also share how to set permissions on each function and menu based on user login.

So, you can apply it to your own project right now.

Awesome right?

To create login system, you can use session library in codeigniter.

 

What is SESSION?

The Session is a class permits you maintain a user’s “state” and track their activity while they browse your site.

It may sound complicated, but it is not.

You will understand clearly after trying it by yourself.

Let’s dive right in.

 

Step 1. Preparation

This is important!

If you missed this step, it means you missed the whole of this tutorial.

Good preparation will determine your success following this tutorial. The better your preparation, the more likely you will succeed in following this tutorial.

Do not skip this step, though it feels complex.

So, what do you need to prepare?

Here’s the list:

#1. Codeiginter

Codeigniter is the main php framework we will use in this tutorial. If you do not have it yet, please download it at the official website: www.codeigniter.com

#2. Bootstrap

Bootstrap is a framework to beautify the user interface (UI). If you do not have it yet, please download it first at the official website: www.getbootstrap.com  

Ok, Let’s continue!

 

Step 2. Database Preparation

In this tutorial, I use mysql as Database Management System (DBMS).

If you also use mysql, you will love this tutorial.

But,

If you are using other DBMS like Oracle, SQL Server, or Maria DB

No, Problem!

Provided you understand SQL (Structured Query Language) better.

Ok, Let's continue!

Please create a database, here I create a database with named login_db.

If you create a database with the same name it will be better.

You can create a database by following the SQL syntax below:

CREATE DATABASE login_db;

That query will generate a database with named login_db.

After that,

Create a table with named tbl_users with structure below:

Database Structure

To create a table structure like the picture above,

You could follow this query:

CREATE TABLE tbl_users(
user_id INT PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(20),
user_email VARCHAR(60),
user_password VARCHAR(40),
user_level VARCHAR(3)
);

After that, insert some data into the tbl_users table by executing query below:

INSERT INTO tbl_users (user_name,user_email,user_password,user_level) 
VALUES 
('M Fikri','fikrifiver97@gmail.com',MD5('123456'),'1'),
('Daria','email2@gmail.com',MD5('123456'),'2')
('Jhon','email3@gmail.com',MD5('123456'),'3');

 

Step 3. Codeigniter Installation

Next,

Extract codeigniter that has been downloaded earlier to www folder (if you use wampserver) or htdocs (if you use XAMPP).

Because I use wampserver. So, I extract it to c:/wamp/www/

And then, rename codeigniter project to be login.

Like this:

Project Name

Open login folder and create new assets folder, then include the bootstrap file inside the assets folder.

So that look like this:

Project Structure

In the picture above can be seen, that in the folder assets there are css and js folder.

Inside the css folder, there is a bootstrap.min.css file

Inside the js folder, there is a bootstrap.min.js file

 

Step 4. Codeigniter Configuration

Next step is the configuration on the codeigniter.

Here are some files you need to configure:

1. Autoload.php

To configure the autoload.php, please open the folder:

application/config/autoload.php

like this:

Autoload

Open autoload.php using text editor like Notepad++ or Sublime Text.

And then find the code below:

$autoload['libraries'] = array();
$autoload['helper'] = array();

Set to be like this:

$autoload['libraries'] = array('database', 'session');
$autoload['helper'] = array('url');

 

2. Config.php

To configure the config.php, please open the folder:

application/config/config.php

like this:

Config

Open config.php file using text editor, and then find the code below:

$config['base_url'] = '';

And then set to be like this:

$config['base_url'] = 'http://localhost/login/';

 

3. Database.php

To configure the database.php, please open the folder:

application/config/database.php

like this:

Database

Open database.php file using text editor, and then find the code below:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        'database' => '',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
);

And then Set to be like this:

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
        'dsn'   => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'login_db',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
);

 

Step 5. Controller

The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.

In this case, we need two controllers. Login.php and Page.php.

First of all, create a controller file controllers/Login.php by the following the code below:

<?php
class Login extends CI_Controller{
  function __construct(){
    parent::__construct();
    $this->load->model('login_model');
  }

  function index(){
    $this->load->view('login_view');
  }

  function auth(){
    $email    = $this->input->post('email',TRUE);
    $password = md5($this->input->post('password',TRUE));
    $validate = $this->login_model->validate($email,$password);
    if($validate->num_rows() > 0){
        $data  = $validate->row_array();
        $name  = $data['user_name'];
        $email = $data['user_email'];
        $level = $data['user_level'];
        $sesdata = array(
            'username'  => $name,
            'email'     => $email,
            'level'     => $level,
            'logged_in' => TRUE
        );
        $this->session->set_userdata($sesdata);
        // access login for admin
        if($level === '1'){
            redirect('page');

        // access login for staff
        }elseif($level === '2'){
            redirect('page/staff');

        // access login for author
        }else{
            redirect('page/author');
        }
    }else{
        echo $this->session->set_flashdata('msg','Username or Password is Wrong');
        redirect('login');
    }
  }

  function logout(){
      $this->session->sess_destroy();
      redirect('login');
  }

}

Second of all, create one more controller file controllers/Page.php by the following the code below:

<?php
class Page extends CI_Controller{
  function __construct(){
    parent::__construct();
    if($this->session->userdata('logged_in') !== TRUE){
      redirect('login');
    }
  }

  function index(){
    //Allowing akses to admin only
      if($this->session->userdata('level')==='1'){
          $this->load->view('dashboard_view');
      }else{
          echo "Access Denied";
      }

  }

  function staff(){
    //Allowing akses to staff only
    if($this->session->userdata('level')==='2'){
      $this->load->view('dashboard_view');
    }else{
        echo "Access Denied";
    }
  }

  function author(){
    //Allowing akses to author only
    if($this->session->userdata('level')==='3'){
      $this->load->view('dashboard_view');
    }else{
        echo "Access Denied";
    }
  }

}

 

Step 6. Model

The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.

In this case we just need one model, that is Login_model.php

So, create a model file models/Login_model.php by the following the code below:

<?php
class Login_model extends CI_Model{

  function validate($email,$password){
    $this->db->where('user_email',$email);
    $this->db->where('user_password',$password);
    $result = $this->db->get('tbl_users',1);
    return $result;
  }

}

 

Step 7. View

The View is the information that is being presented to a user.

A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.

In this case, we need two views. That are login_view.php as login form and dashboard_view.php as dashboard after login.

So, first of all, create a view file views/login_view.php by the following the code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Sign In</title>
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>

      <div class="container">
       <div class="col-md-4 col-md-offset-4">
         <form class="form-signin" action="<?php echo site_url('login/auth');?>" method="post">
           <h2 class="form-signin-heading">Please sign in</h2>
           <?php echo $this->session->flashdata('msg');?>
           <label for="username" class="sr-only">Username</label>
           <input type="email" name="email" class="form-control" placeholder="Email" required autofocus>
           <label for="password" class="sr-only">Password</label>
           <input type="password" name="password" class="form-control" placeholder="Password" required>
           <div class="checkbox">
             <label>
               <input type="checkbox" value="remember-me"> Remember me
             </label>
           </div>
           <button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
         </form>
       </div>
       </div> <!-- /container -->

    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

Second of all, create one more view file views/dashboard_view.php by the following the code below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Welcome</title>
    <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>" rel="stylesheet">
  </head>
  <body>
    <div class="container">
      <div class="row">
      <nav class="navbar navbar-default">
          <div class="container-fluid">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="#">LOGO</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                <!--ACCESS MENUS FOR ADMIN-->
                <?php if($this->session->userdata('level')==='1'):?>
                  <li class="active"><a href="#">Dashboard</a></li>
                  <li><a href="#">Posts</a></li>
                  <li><a href="#">Pages</a></li>
                  <li><a href="#">Media</a></li>
                <!--ACCESS MENUS FOR STAFF-->
                <?php elseif($this->session->userdata('level')==='2'):?>
                  <li class="active"><a href="#">Dashboard</a></li>
                  <li><a href="#">Pages</a></li>
                  <li><a href="#">Media</a></li>
                <!--ACCESS MENUS FOR AUTHOR-->
                <?php else:?>
                  <li class="active"><a href="#">Dashboard</a></li>
                  <li><a href="#">Posts</a></li>
                <?php endif;?>
              </ul>
              <ul class="nav navbar-nav navbar-right">
                <li><a href="<?php echo site_url('login/logout');?>">Sign Out</a></li>
              </ul>
            </div><!--/.nav-collapse -->
          </div><!--/.container-fluid -->
        </nav>

        <div class="jumbotron">
          <h1>Welcome Back <?php echo $this->session->userdata('username');?></h1>
        </div>

      </div>
    </div>

    <script src="<?php echo base_url('assets/js/bootstrap.min.js');?>"></script>
  </body>
</html>

 

Step 8. Setting Default Controller

Set the default controller to 'login' for the login form to appear the first time the website is loaded.

To set the default controller, you can configure the routes.php, please open the folder:

application/config/routes.php

like this:

Default Controller

And then find the code below:

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

After that, set to be like this:

$route['default_controller'] = 'login';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

 

Step 8. Done

To test whether the login system is running properly. Open your browser, and following the url below:

http://localhost/login/

Then it will appear login form below:

Login Form

First of all, I try login as admin by username: fikrifiver97@gmail.com and password: 123456.

Login as Admin

So that, we can see the all of menus will appear.

Dashboard admin

Second of all, I try login as staff by username: email2@gmail.com and password: 123456.

Dashboard Staff

Lastly, I try to login as author by username: email3@gmail.com and password: 123456

Dashboard Author

Congratulations, you did it.!

 

CONCLUSION

In today's tutorial is about how to create multi level user login system using codeigniter.

To create login system, we use codeigniter session library.

The Session class permits you maintain a user’s “state” and track their activity while they browse your site.

In this tutorial, you are already learned how to create multi level user login using codeigniter, step by step.

Not Only that, you also have learned how to manage the session and set the permissions of each function and menu based on user login.

-Thank You-

Download Source Code

Comments (23)

syaeful, 28 August 2018 22:20 -

Mas fikri, saya mau minta bantuanya kalau mau setting codeigniter di webserver dan subdomain gimana yah pakai codeigniter jadi saya buat dua2nya pakai codeigniter untuk yg di root awal sudah berjalan tp saat saya coba buka yg subdomain bermasalah error 404. biar bisa dibaca disubdomain apa yang perlu saya setting lg...? terimakasih mohon bantuanya. ????????????

M Fikri, 03 September 2018 17:11 -

Tinggal di atur di config.php gan!
$config['base_url'] = 'http://subdomain.domain.com/';

Japhet Mnyetta, 01 November 2018 13:49 -

This tutorial is amazing because I was looking on a way to manipulate sessions the way I wanted then I have found it so now I can build my own authentication systems Very good tutorial

M Fikri, 21 November 2018 11:29 -

Thank You.

Ilman H Oriza, 07 December 2018 22:36 -

gila, tutorial paling simpel, saya ajah yang beginner mudah sekali memahami tutorial ini, thank om terus berkarya dalam tulisan :) salam coding.

lelemkop, 26 January 2019 00:55 -

hi, I followed your guide and the system works perfectly. Now I would need to create and reset users. How can I do?

JasonSmibiabrah, 05 February 2019 05:12 -

Thank you so much, this is really great tutorial.

M Fikri, 07 February 2019 21:23 -

You are welcome Jason. Thanks Back.

RIDHO, 14 February 2019 16:19 -

You guys so amazing, simple sharing but very useful and helpful.., especially for beginners like me who are new to codeigniter.

Jesus, 01 March 2019 22:29 -

What version of Bootstrap did you use?

M Fikri, 08 March 2019 09:25 -

Jesus, I am using bootstrap v3.3.7

Maroof Khan, 04 April 2019 18:14 -

This is a good tutorial to learn login system in Detail

nasra, 18 April 2019 19:40 -

when i try to run the code am getting this error "In order to use the Session class you are required to set an encryption key in your config file." please help out....am stacked

M Fikri, 19 April 2019 08:16 -

Hi Nasra,
Find the code below in the config.php file:

$config['encryption_key'] = 'FALSE';

And then, change it to be like this:

$config['encryption_key'] = 'TRUE';

 

unisun, 27 July 2019 17:25 -

good explanation tq for great tutorial

M Fikri, 27 July 2019 20:38 -

You are welcome, and thanks for visit my site.

masih, 01 October 2020 11:59 -

hay hi, thank you so much for your contribution, could you please do it in codeigniter 4

edward, 08 November 2020 14:17 -

thanks. very useful and easy to understand ....

vibin, 29 December 2020 18:33 -

wonderful tutorial man its very helpful thank you so much your valuable time

easymathematics, 05 January 2021 01:57 -

Nice tutorial, easy to understand, easy to extend, easy to work with. :)

dastgir, 18 July 2021 17:40 -

Nice tut????

muuHag, 19 August 2021 10:19 -

Hello everyone on this forum - thanks. My name is Mark and i am from luxembourg best regards :)

Leave a Comment