2016-04-14

Codeigniter 3 Admin Panel with "FULL Source Code"

level : medium


Did you know great websites like ebay.com, amazon.com, or wikipedia.com can  store or retrieve data to/from their database? Can you imagine how to manage all systems and data from one place? Yes, this is called Admin Panel. (This can be simple or complex depends on case/data needed so it's flexible) Today, we will create Admin Panel system with Codeigniter 3 PHP framework (latest update on 2016). Don't be panic, we study step by step and if you need the source code to develop you can download in bottom

This system covers:
  • Login and logout system
  • Auto restrict, if user isn't member
  • Retrieve data  from database
  • Session 
  • Clean url 
  • Sample page for module and user management (read-only from database)
So, we have to take plan. 
  1. Setting your config.php in folder application/config/config.php. Set your base url to access your application. Maybe like this
    $config['base_url'] = 'http://localhost/admin';
    //your location in localhost

  2. Setting your database configuration in application/config/database.php
    ...
    'hostname' => 'localhost',
     'username' => 'root',
     'password' => '',
     'database' => 'admin_ci',
     'dbdriver' => 'mysqli',
    ...
    

  3. Add file .htaccess below folder application, and system to remove index.php in your codeigniter address so URL like this: localhost/admin/function. (this is optional, but if you don't remove this you have to set base url to: localhost/admin/index.php - on step 1)
    Codeigniter 3 Admin Panel with Full Source Code
    write this code
    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|assets|robots\
    .txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]

  4. Setting default first access of your apllication in application/config/routes.php. Change default controller into your controller. Maybe likes
    $route['default_controller'] = 'login'; 
    //name of your controller
    

  5. Starting your code

  6. First, we make database called admin_ci based on step 2 (but, if you want to use your name is fine but remember to change the configuration also)
    CREATE TABLE `modules` (
      `id` tinyint(5) NOT NULL,
      `name` varchar(30) NOT NULL,
      `show` enum('0','1') NOT NULL,
      `read` enum('0','1') NOT NULL,
      `update` enum('0','1') NOT NULL,
      `delete` enum('0','1') NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
    INSERT INTO `modules` (`id`, `name`, `show`, `read`, 
    `update`, `delete`) VALUES
    (1, 'Admin Page', '1', '1', '1', '0'),
    (2, 'User Management', '1', '1', '0', '0');
    CREATE TABLE `users` (
      `id` int(255) NOT NULL,
      `name` varchar(50) NOT NULL,
      `username` varchar(255) NOT NULL,
      `password` varchar(255) NOT NULL,
      `level` varchar(15) NOT NULL,
      `status` enum('Active','None') NOT NULL
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    INSERT INTO `users` (`id`, `name`, `username`, 
    `password`, `level`, `status`) VALUES
    (26, 'Steven Ring', 'admin', 'admin123', 'Admin', 
    'Active'),(27, 'Bruno', 'operator', 'operator123', 
    'Operator', 'Active');
    ALTER TABLE `modules`
      ADD PRIMARY KEY (`id`);
    ALTER TABLE `users`
      ADD PRIMARY KEY (`id`),
      ADD UNIQUE KEY `username` (`username`);
    ALTER TABLE `modules`
      MODIFY `id` tinyint(5) NOT NULL AUTO_INCREMENT, 
      AUTO_INCREMENT=3;
    ALTER TABLE `users`
      MODIFY `id` tinyint(5) NOT NULL AUTO_INCREMENT, 
      AUTO_INCREMENT=28;
    

    Info! in Codeigniter 3 you should name your each class start from uppercase or capital, see the reference
  7. Then write the code.We start from Controllers :

    • Login.php
      class Login extends CI_Controller {
      
        public function __construct() {
          
          parent::__construct(); 
          $this->load->helper(array('form', 'url'));
          $this->load->library('form_validation');
          $this->load->model('Login_auth_db');
          $this->load->library('session');
      
        }
          
        public function index() {
          
          $this->load->view('login');
          
        }
        
        public function login_auth() {
          
          // create the data object
          $data = new stdClass();
          
          // load form helper and validation library
          $this->load->helper('form');
          $this->load->library('form_validation');
          $this->load->library('session');
          
          // set validation rules
          $this->form_validation->set_rules('username'
          , 'Username', 'required|alpha_numeric');
          $this->form_validation->set_rules('password'
          , 'Password', 'required');
          
        if ($this->form_validation->run() == false) {
            
            // validation not ok, send validation 
            errors to the view
            $this->load->view('login');
            
          } else {
            
            // set variables from the form
          $username = $this->input->post('username');
          $password = $this->input->post('password');
            
            if ($this->Login_auth_db->login($username,
       $password)) {
              $user_data = $this->Login_auth_db
        ->get_user_data($username);
              
              $user_detail = array(
                'name'  => $user_data['name'],
                'username'  => $user_data['username'],
                'level'  => $user_data['level'],
                'status'  => $user_data['status']
              );
              $this->session->set_userdata(
      'user_data_session', $user_detail);
              $this->session->set_userdata
        ('logged_in', true);
              
              // user login ok
              $data_to_view['selected'] = 'dashboard';
              $data_to_view['content'] = 'dashboard';
              $this->load->view('base_view', 
        $data_to_view);
              
            } else {
              
              // login failed
              $data->error = 'Wrong username or 
      password.';
              
              // send error to the view
              $this->load->view('login', $data);
              
            }
            
          }
          
        }
        
        public function home() {
          
          $data['content'] = 'dashboard';
          $this->load->view('base_view', $data);
        
        }
      
      }
      

      explanation : we have to call library and helper to handle some other functions like form validation, session, and model to retrieve data from database.

    • Logout.php
      public function index() {
          
          $this->session->unset_userdata(
      'user_data_session');
          $this->session->set_userdata('logged_in',
       false);
          redirect(base_url().Login);
        }
      

    • Home.php
      public function __construct() {
          
          parent::__construct(); 
          $this->load->helper(array('url'));
              $this->load->library('form_validation');
          $this->load->library('session');
          
          // to protect the controller to be accessed 
      only by registered users
            if(!$this->session->userdata('logged_in'))
         {
            
            redirect('login', 'refresh');
                 
          }
      
        }
          
        public function index() {
          
          $data['content'] = 'dashboard';
          $this->load->view('base_view', $data);      
        
        }
      

    • Modules.php
      public function index() {
          
          $data   = array();  
          $module_data = $this->Modules_db->select();
          
          if ($module_data != null) {
            
            $data['result'] = $module_data;
            //to check weather have module data or not
            $data['checking_status'] = 1;
            
          } else {
            
            $data['checking_status'] = 0;
            
          }
              
          $data['content'] = 'modules';
          $this->load->view('base_view', $data);
        
        }
      

    • Users.php
      public function index() {
          
          $data   = array();  
          $user_data = $this->Users_db->select();
          
          if ($user_data != null) {
            
            $data['result'] = $user_data;
            $data['checking_status'] = 1;
            
          } else {
            
            $data['checking_status'] = 0;
            
          }
          
          $data['content'] = 'users';
          $this->load->view('base_view', $data);
        }
      

    • And make the same to others controller like Profile.php, Settings.php, Blank_page.php. (To see complete source is available in link download below)




  8. Next, we make the Model. We would make at least 3 Class of model, Login_auth_db.php, Modules_db.php and Users.php

    • Login_auth_db.php
      Class Login_auth_db extends CI_Model {
        
        public function __construct() {
          
          parent::__construct();
          $this->load->database();
          
        }
        
        function login($username, $password) {
          
          $this->db->select('*');
          $this->db->from('users');
          $this->db->where('username', $username);
          $this->db->where('password', $password);
          $query = $this->db->get()->row();
          
          if (!empty($query)) {
            
            return true;
            
          } else {
            
            return false;
            
          }
          
        }
        
        function get_user_data($username) {
          
          //$this->load->library('session');
          $this->db->select('*');
          $this->db->from('users');
          $this->db->where('username', $username);  
          $query = $this->db->get();
          
          $user_data = array(
            'username'  => $query->row('username'),
            'status'  => $query->row('status'),
            'name'  => $query->row('name'),
            'level'  => $query->row('level')
            );
          
          return $user_data;
          
        }
        
      }
      

    • Modules_db.php
      public function __construct() {
          
          parent::__construct();
          $this->load->database();
          
        }
        
        function select() {
          
          $this->db->select('*');
          $this->db->from('modules');  
          $query = $this->db->get();
              return $result = $query->result();
              
        }
      

    • Next, you can make your own Users_db.php to load data.




  9. Last, we write Views

    • Base_view.php
      This class make base template of your admin panel, constantly
      load->library('session');
      $user_detail = $this->session->userdata
      ('user_data_session');
      $name = $user_detail['name'];
      
      if($content == 'dashboard') { $this->load
      ->view('home'); $selected = $content; 
      $content='';}
      if($content == 'modules') { $this->load->
      view('modules'); $selected = $content; 
      $content='';}
      if($content == 'users') { $this->load->
      view('users'); $selected = $content; 
      $content='';}
      if($content == 'blank_page1') { $this->
      load->view('blank_page1'); $selected = 
      $content; $content='';}
      if($content == 'blank_page2') { $this->
      load->view('blank_page2'); $selected = 
      $content; $content='';}
      if($content == 'settings') { $this->load
      ->view('settings'); $selected = $content; 
      $content='';}
      if($content == 'profile') { $this->load->
      view('profile'); $selected = $content; 
      $content='';}
      ?>
      
      <!-- Navigation -->
        <nav class="navbar navbar-inverse 
      navbar-fixed-top" role="navigation">
        <!-- Brand and toggle get grouped 
        for better mobile display -->
        <div class="navbar-header">
      <button class="navbar-toggle" data-target
      =".navbar-ex1-collapse" data-toggle=
      "collapse" type="button">
        <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="<?php echo 
        base_url();?>home">Admin Panel</a>
        </div>
      <!-- Top Menu Items -->
        <ul class="nav navbar-right top-nav">
      <li class="dropdown">
        <a class="dropdown-toggle" data-toggle=
        "dropdown" href="#"><i class="fa fa-user">
        </i> 
        <?php echo $name;?> <b class="caret"></b>
        </a>
        <ul class="dropdown-menu">
      <li>
        <a href="<?php echo base_url(); ?>
        profile">
        <i class="fa fa-fw fa-user"></i> 
        Profile</a>
        </li>
      <li>
        <a href="<?php echo base_url(); ?>
        settings">
        <i class="fa fa-fw fa-gear"></i> 
        Settings</a>
        </li>
      <li class="divider"></li>
      <li>
        <a href="<?php echo base_url(); ?>
        logout">
        <i class="fa fa-fw fa-power-off"></i>
        Log Out</a>
        </li>
      </ul>
      </li>
      </ul>
      <!-- Sidebar Menu Items - These 
      collapse to the responsive navigation
       menu on small screens -->
        <div class="collapse navbar-collapse 
        navbar-ex1-collapse">
      <ul class="nav navbar-nav side-nav">
        <?php 
         if ($selected == 'dashboard')  echo 
       '<li class="active" >';
         else echo '<li>';
         ?>
            <a href="<?php echo base_url(); ?>home">
         <i class="fa fa-fw fa-dashboard"></i> 
         Dashboard<?php echo '';?></a>
            </li>
          <?php 
         if ($selected == 'modules')  echo 
       '<li class="active" >';
         else echo '<li>';
         ?>
            <a href="<?php echo base_url(); ?>
         modules"><i class="fa fa-fw 
         fa-desktop">
         </i> Modules</a>
            </li>
          <?php 
         if ($selected == 'users') echo '<li 
       class="active" >';
         else echo '<li>';
         ?>
            <a href="<?php echo base_url(); ?>users">
         <i class="fa fa-fw fa-edit"></i> 
         Users</a>
            </li>
          <?php 
         if ($selected == 'blank_page1' || 
       $selected == 'blank_page2') echo '<li 
       class="active" >';
         else echo '<li>';
         ?>
            <a href="javascript:;" data-toggle=
         "collapse" data-target="#demo"><i 
         class="fa fa-fw fa-file"></i> Blank
         Page <i class="fa fa-fw 
         fa-caret-down"></i></a>
            <ul id="demo" class="collapse">
              <li>
              <a href="<?php echo base_url(); ?>
        blank_page/blank_page1"> Blank 
        Page 1</a>
              </li>
              <li>
              <a href="<?php echo base_url(); ?
        >blank_page/blank_page2"> Blank 
        Page 2</a>
        </li>
      </ul>
      </li>
      </ul>
      </div>
      <!-- /.navbar-collapse -->
        </nav>
      

    • Then, make login page, Login.php
      <div class="container">
      <div class="card card-container">
        <img id="profile-img" class="profile-img-card" 
        src="<?php echo base_url();?>assets/image/
        avatar_2x.png" />     
          
        <?php echo (!empty($error) ? '<p class=
          "alert alert-danger"><a href="#" class=
          "close" data-dismiss="alert" aria-label=
          "close">&times;</a>'.$error.'</p>' : '');
       ?> 
          
        <form class="form-signin" action="<?php echo
        base_url(); ?>Login/login_auth" method="post">
        <span id="reauth-email" class="reauth-email"
        ></span>
        <input type="text" id="inputUsername" class=
        "form-control" placeholder="Username" name=
        "username" required autofocus>
        <input type="password" id="inputPassword" 
        class="form-control" placeholder="Password" 
        name="password" required>
        <div id="remember" class="checkbox">
          <label>
          <input type="checkbox" value="remember-me">
       Remember me
          </label>
        </div>
        <button class="btn btn-lg btn-primary 
      btn-block  btn-signin" type="submit">
      Sign in</button>
        </form><!-- /form -->
        <a href="#" class="forgot-password">
        Forgot the password?
        </a>
      </div><!-- /card-container -->
      </div><!-- /container -->
      

    • Codeigniter 3 Admin Panel with FULL Source Code

    • Home.php for dashboard interface
      <div class="row">
        <div class="col-lg-12">
          <ol class="breadcrumb">
            <li class="active">
              <i class="fa fa-file"></i> Dashboard
            </li>
          </ol>
        </div>
        <div class="col-lg-6">
          <h4>Welcome to the System, <i><?php 
      echo $level; ?></i>.</h4>
          <p>Hope you joy the day. Have fun</p>
        </div>
      </div>
      
    • Codeigniter 3 Admin Panel with FULL Source Code

    • Example of Module page to read data from database in Modules.php
      <div id="wrapper">  
        <div id="page-wrapper">
          <div class="container-fluid">
            <!-- Page Heading -->
            <div class="row">
              <div class="col-lg-12">
                <ol class="breadcrumb">
                  <li class="active">
                    <i class="fa fa-desktop"></i> 
           Modules
                  </li>
                </ol>
              </div>
              <div class="col-lg-6">
                <div class="table-responsive">
                  <table class="table table-hover 
         table-striped">
                    <thead>
                      <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Show</th>
                        <th>Read</th>
                        <th>Update</th>
                        <th>Delete</th>
                      </tr>
                    </thead>
                    <tbody>
                      <?php
                        if ($checking_status == 1)
            {
                          foreach($result as $r) {?>
                            <tr>
                            <td><?php echo $r->id; 
         ?></td>
                            <td><?php echo $r->name;
         ?></td>
                            <td><?php echo $r->show 
         == 1 ? 'yes' : 'no'; ?></td>
                            <td><?php echo $r->read 
         == 1 ? 'yes' : 'no'; ?></td>
                            <td><?php echo $r->update
         == 1 ? 'yes' : 'no'; ?></td>
                            <td><?php echo $r->delete
         == 1 ? 'yes' : 'no'; ?></td>
                            </tr>
                            <?php
                          }
                        } else {
                          
                          echo '<td colspan=6 style=
         "text-align:center">empty
         data module</td>';
                          
                        }
      ?>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      Codeigniter 3 Admin Panel with FULL Source Code



  • By same method you can make User page in Users.php. The interface should shows like : 
    Codeigniter 3 Admin Panel with FULL Source Code
  • This is your files  :
    Link download1 (short code)
    Link download2  (Full source code)
    Continue Reading

    2016-03-31

    Simple Tutorial : Codeigniter Login System Tutorial Without Database Connection

    level : easy 


    Did you know? All of systems has the security to block uninvited user for come. Just some users have key (like username, password, or captcha) allowed. Today, we will learn about login system in PHP with Codeigniter framework but you can run without any database connection. - Only for learning, not for creating big system - It will really simple. You just need files in your Codeigniter controller and views. It will needs login.php and logout.php in controller and login.php  and admin.php in views.

    Steps:
    1. Preparing Codeigniter framework
    2. Create login.php in your controller
    3. Create logout.php in your controller
    4. Create login.php in your views
    5. Create admin.php in your views
    6. Run program

    Information: we will create login system with "session" to save temporary data of user

    Create login.php in Controller
    public function index() {
     $this->load->view('login');
    
    }
    
    public function login() {
    
     $this->load->library('session');
     $this->load->library('form_validation');
     $this->load->helper('url'); 
     $this->form_validation->set_rules('username','Username',
    'trim|required');
     $this->form_validation->set_rules('password','Password',
    'trim|required|md5');
     if($this->form_validation->run()==false){
      $this->index();
     }else{
      $user_session=array(
       'Username'      => $this->input->post('username'),
       'Password'      => $this->input->post('password'),
       'is_logged_in'  => 1
      );
      $this->session->set_userdata('userlogin',$user_session);
      $this->admin();
     }
    
    }
    
    public function admin() {
     $this->load->view('admin');
    
    }
    

    Create logout.php in Controller
    public function index() {
    
     //$this->load->view('logout');
     $this->load->view('login'); 
    
    }
    
    public function logout() {
    
     $this->load->library('session');
     $this->session->unset_userdata('userlogin');
     $this->index();
     
    }
    

    Create login.php in Views
    <form class="form-horizontal" role="form" action=
    "<?php echo 'http://localhost/answers/index.php/login/
    login'; ?>" method="post">
     <div class="form-group">
       <label class="control-label col-sm-2" for="username"
    >Username:</label>
       <div class="col-sm-10">
      <input type="username" class="form-control" id="username"
     name="username" placeholder="Enter username">
       </div>
     </div>
     <div class="form-group">
       <label class="control-label col-sm-2" for="pwd">
    Password:</label>
       <div class="col-sm-10">          
      <input type="password" class="form-control" id="password"
     name="password" placeholder="Enter password">
       </div>
     </div>
     <div class="form-group">        
       <div class="col-sm-offset-2 col-sm-10">
      <div class="checkbox">
        <label><input type="checkbox"> Remember 
    me</label>
      </div>
       </div>
     </div>
     <div class="form-group">        
       <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">
    Login</button>
       </div>
     </div>
    </form>
    

    Create admin.php in Views
    <form class="navbar-form navbar-right" role=
    "search" action="<?php echo 'http://localhost/answers
    /index.php/logout/logout'; ?>">
     <button type="submit" class="btn btn-default">
    Logout</button>
    </form>
    <h2>Welcome to the system, 
    <?php 
     $this->load->library('session');
     $login_session = $this->session->userdata('userlogin');
     //$username = $this->session->userdata('userlogin');
     echo $login_session['Username'];
    ?>
    </h2>
    
    Run program

    - Login Page -
    Codeigniter Login System Tutorial Without Database Connection

    Write your url address, example http://localhost/answers/index.php/login/login to display your login form.

    - Admin Page -
    Codeigniter Login System Tutorial Without Database Connection

    
    
    
    
    
    
    
    
    
    
    
    
    We will get the greeting and also mention our name / username. Then if you click your logout button it will back into login page


    Those files from google drive. You can download the one at :
    Link download1 (short program)
    Link download2  (complete files)
    Continue Reading

    About Us

    Like Us

    Labels

    Designed By Blogger Templates