Sie sind auf Seite 1von 29

 Home

 About
 Blog
 Contact

25

How to make multi level user login using codeigniter


[Complete Tutorial]
 July 20, 2018
 M Fikri Setiadi
 Codeigniter
 4,998 Views
 4 Comments

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:

1CREATE 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:
To create a table structure like the picture above,

You could follow this query:

1
CREATE TABLE tbl_users(
2user_id INT PRIMARY KEY AUTO_INCREMENT,
3user_name VARCHAR(20),
4user_email VARCHAR(60),
5user_password VARCHAR(40),
6user_level VARCHAR(3)
);
7

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

1INSERT INTO tbl_users (user_name,user_email,user_password,user_level)


2VALUES
3('M Fikri','fikrifiver97@gmail.com',MD5('123456'),'1'),
4('Daria','email2@gmail.com',MD5('123456'),'2')
5('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:
Open login folder and create new assets folder, then include the bootstrap file inside the assets
folder.

So that look like this:


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:

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

And then find the code below:

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

Set to be like this:

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


2$autoload['helper'] = array('url');

2. Config.php

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


application/config/config.php

like this:

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

1$config['base_url'] = '';

And then set to be like this:

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

3. Database.php

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

application/config/database.php

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

1
2 $active_group = 'default';
3 $query_builder = TRUE;
4 $db['default'] = array(
5
'dsn' => '',
6 'hostname' => 'localhost',
7 'username' => '',
8 'password' => '',
9 'database' => '',
'dbdriver' => 'mysqli',
10 'dbprefix' => '',
11 'pconnect' => FALSE,
12 'db_debug' => (ENVIRONMENT !== 'production'),
13 'cache_on' => FALSE,
14 'cachedir' => '',
'char_set' => 'utf8',
15 'dbcollat' => 'utf8_general_ci',
16 'swap_pre' => '',
17 'encrypt' => FALSE,
18 'compress' => FALSE,
'stricton' => FALSE,
19 'failover' => array(),
20 'save_queries' => TRUE
21);
22
23
24

And then Set to be like this:

1
2
3 $active_group = 'default';
4 $query_builder = TRUE;
5 $db['default'] = array(
6
'dsn' => '',
7 'hostname' => 'localhost',
8 'username' => 'root',
9 'password' => '',
10 'database' => 'login_db',
'dbdriver' => 'mysqli',
11 'dbprefix' => '',
12 'pconnect' => FALSE,
13 'db_debug' => (ENVIRONMENT !== 'production'),
14 'cache_on' => FALSE,
15 'cachedir' => '',
'char_set' => 'utf8',
16 'dbcollat' => 'utf8_general_ci',
17 'swap_pre' => '',
18 'encrypt' => FALSE,
19 'compress' => FALSE,
'stricton' => FALSE,
20 'failover' => array(),
21 'save_queries' => TRUE
22);
23
24

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:

1 <?php
2 class Login extends CI_Controller{
function __construct(){
3 parent::__construct();
4 $this->load->model('login_model');
5 }
6
7 function index(){
8 $this->load->view('login_view');
}
9
10 function auth(){
11 $email = $this->input->post('email',TRUE);
12 $password = md5($this->input->post('password',TRUE));
13 $validate = $this->login_model->validate($email,$password);
14 if($validate->num_rows() > 0){
15 $data = $validate->row_array();
16 $name = $data['user_name'];
17 $email = $data['user_email'];
$level = $data['user_level'];
18 $sesdata = array(
19 'username' => $name,
20 'email' => $email,
21 'level' => $level,
22 'logged_in' => TRUE
23 );
24 $this->session->set_userdata($sesdata);
25 // access login for admin
if($level === '1'){
26 redirect('page');
27
28 // access login for staff
29 }elseif($level === '2'){
30 redirect('page/staff');
31
// access login for author
32 }else{
33 redirect('page/author');
34 }
35 }else{
36 echo $this->session->set_flashdata('msg','Username or Password is
Wrong');
37 redirect('login');
38 }
39 }
40
41 function logout(){
$this->session->sess_destroy();
42
redirect('login');
43 }
44
45}
46
47
48
49
50
51
Second of all, create one more controller file controllers/Page.php by the following the code
below:

1
2
3
4 <?php
5 class Page extends CI_Controller{
function __construct(){
6 parent::__construct();
7 if($this->session->userdata('logged_in') !== TRUE){
8 redirect('login');
9 }
}
10
11 function index(){
12 //Allowing akses to admin only
13 if($this->session->userdata('level')==='1'){
14 $this->load->view('dashboard_view');
}else{
15
echo "Access Denied";
16 }
17
18 }
19
20 function staff(){
21 //Allowing akses to staff only
if($this->session->userdata('level')==='2'){
22 $this->load->view('dashboard_view');
23 }else{
24 echo "Access Denied";
25 }
26 }
27
function author(){
28 //Allowing akses to author only
29 if($this->session->userdata('level')==='3'){
30 $this->load->view('dashboard_view');
31 }else{
echo "Access Denied";
32 }
33 }
34
35}
36
37
38

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:

1
2 <?php
class Login_model extends CI_Model{
3
4 function validate($email,$password){
5 $this->db->where('user_email',$email);
6 $this->db->where('user_password',$password);
7 $result = $this->db->get('tbl_users',1);
return $result;
8 }
9
10}
11

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:

1 <!DOCTYPE html>
<html lang="en">
2 <head>
3 <meta charset="utf-8">
4 <title>Sign In</title>
5 <link href="<?php echo base_url('assets/css/bootstrap.min.css');?>"
rel="stylesheet">
6 </head>
7 <body>
8
9 <div class="container">
10 <div class="col-md-4 col-md-offset-4">
11 <form class="form-signin" action="<?php echo
site_url('login/auth');?>" method="post">
12 <h2 class="form-signin-heading">Please sign in</h2>
13 <?php echo $this->session->flashdata('msg');?>
14 <label for="username" class="sr-only">Username</label>
15 <input type="email" name="email" class="form-control"
placeholder="Email" required autofocus>
16 <label for="password" class="sr-only">Password</label>
17 <input type="password" name="password" class="form-control"
18placeholder="Password" required>
19 <div class="checkbox">
<label>
20 <input type="checkbox" value="remember-me"> Remember me
21 </label>
22 </div>
23 <button class="btn btn-lg btn-primary btn-block"
24 type="submit">Sign in</button>
</form>
25 </div>
26 </div> <!-- /container -->
27
28 <script src="<?php echo
29 base_url('assets/js/bootstrap.min.js');?>"></script>
</body>
30</html>
31

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

<!DOCTYPE html>
1 <html lang="en">
2 <head>
3 <meta charset="utf-8">
4 <title>Welcome</title>
<link href="<?php echo base_url('assets/css/bootstrap.min.css');?>"
5
rel="stylesheet">
6 </head>
7 <body>
8 <div class="container">
9 <div class="row">
<nav class="navbar navbar-default">
10 <div class="container-fluid">
11 <div class="navbar-header">
12 <button type="button" class="navbar-toggle collapsed" data-
13 toggle="collapse" data-target="#navbar" aria-expanded="false" aria-
14 controls="navbar">
<span class="sr-only">Toggle navigation</span>
15 <span class="icon-bar"></span>
16 <span class="icon-bar"></span>
17 <span class="icon-bar"></span>
18 </button>
<a class="navbar-brand" href="#">LOGO</a>
19 </div>
20 <div id="navbar" class="navbar-collapse collapse">
21 <ul class="nav navbar-nav">
22 <!--ACCESS MENUS FOR ADMIN-->
23 <?php if($this->session->userdata('level')==='1'):?>
<li class="active"><a href="#">Dashboard</a></li>
24 <li><a href="#">Posts</a></li>
25 <li><a href="#">Pages</a></li>
26 <li><a href="#">Media</a></li>
<!--ACCESS MENUS FOR STAFF-->
27 <?php elseif($this->session->userdata('level')==='2'):?>
28 <li class="active"><a href="#">Dashboard</a></li>
29 <li><a href="#">Pages</a></li>
30 <li><a href="#">Media</a></li>
<!--ACCESS MENUS FOR AUTHOR-->
31 <?php else:?>
32 <li class="active"><a href="#">Dashboard</a></li>
33 <li><a href="#">Posts</a></li>
34 <?php endif;?>
35 </ul>
<ul class="nav navbar-nav navbar-right">
36 <li><a href="<?php echo site_url('login/logout');?>">Sign
37Out</a></li>
38 </ul>
39 </div><!--/.nav-collapse -->
</div><!--/.container-fluid -->
40 </nav>
41
42 <div class="jumbotron">
43 <h1>Welcome Back <?php echo $this->session-
44>userdata('username');?></h1>
45 </div>
46
</div>
47 </div>
48
49 <script src="<?php echo
50base_url('assets/js/bootstrap.min.js');?>"></script>
51 </body>
52</html>
53
54
55
56
57

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:
And then find the code below:

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

After that, set to be like this:

1$route['default_controller'] = 'login';
2$route['404_override'] = '';
3$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:


First of all, I try login as admin by username: fikrifiver97@gmail.com and password: 123456.
So that, we can see the all of menus will appear.

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

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-

Share:

Twitter
Facebook
25
Google+
Linked In
Pinterest
1
Whats App

Latest Articles

7 Steps to Create Simple CRUD application using Node.js, Express, and MySQL M Fikri
Setiadi 27 Nov

How To Create Chart Using Codeigniter and Morris.js M Fikri Setiadi 27 Sep

Learn Node.js from Scratch (Step by Step) M Fikri Setiadi 23 Aug


Codeigniter Tutorial for Beginners [Best Practice] M Fikri Setiadi 31 Jul

How to Upload files using Codeigniter and Ajax [Complete Tutorial] M Fikri Setiadi 01 Mar

Codeigniter Autocomplete with Jquery UI [Complete Guide] M Fikri Setiadi 20 Feb

CRUD Datatables Server Side Using Ignited Datatables [COMPLETE TUTORIAL] M


Fikri Setiadi 09 Feb

How to Create a Shopping Cart Using Codeigniter and Ajax [FULL TUTORIAL] M Fikri
Setiadi 29 Jan

How to Upload Image in Codeigniter with Dropify Style [FULL TUTORIAL] M Fikri
Setiadi 26 Jan

CRUD Without Reload Page Using Ajax and Codeigniter [FULL TUTORIAL] M Fikri
Setiadi 25 Jan
Most Popular

CRUD Without Reload Page Using Ajax and Codeigniter [FULL TUTORIAL] M Fikri
Setiadi 25 Jan

How to Create a Shopping Cart Using Codeigniter and Ajax [FULL TUTORIAL] M Fikri
Setiadi 29 Jan

How to Upload files using Codeigniter and Ajax [Complete Tutorial] M Fikri Setiadi 01 Mar

Codeigniter Autocomplete with Jquery UI [Complete Guide] M Fikri Setiadi 20 Feb

How to Upload Image in Codeigniter with Dropify Style [FULL TUTORIAL] M Fikri
Setiadi 26 Jan

CRUD Datatables Server Side Using Ignited Datatables [COMPLETE TUTORIAL] M


Fikri Setiadi 09 Feb

Learn Node.js from Scratch (Step by Step) M Fikri Setiadi 23 Aug

Codeigniter Tutorial for Beginners [Best Practice] M Fikri Setiadi 31 Jul

How To Create Chart Using Codeigniter and Morris.js M Fikri Setiadi 27 Sep

7 Steps to Create Simple CRUD application using Node.js, Express, and MySQL M Fikri
Setiadi 27 Nov

Sponsorship:
CRUD Without Reload Page Using Ajax and Codeigniter [FULL
TUTORIAL]

How to Create a Shopping Cart Using Codeigniter and Ajax [FULL


TUTORIAL]
How to Upload files using Codeigniter and Ajax [Complete Tutorial]
25

Comments (4)

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.

Leave a Comment

25

Copyright © 2017-2019 by mfikri.com | All Right Reserved

English (EN) | Indonesia (ID)






25

Das könnte Ihnen auch gefallen