Create Login System with CodeIgniter MVC Model

Hello, I am a Core PHP programmer and currently learning MVC with codeigniter and bootstrap. So, don't expect some expert level stuff. So Let Begin.

What the hell is MVC?


I am not a reader as I want to code quickly, Here is a diagram to help us understand

Image taken from betterexplained.com. To read more Click here

After understanding the image, it can be presumed that HTML stuff will go to View section. Controllers will be our PHP scripts and boring databases will be in model section. Currently I am using Apache server in WAMP. If I am using MVC, I don't want to use it on simple website. Why should I give myself an headache to adopt it on a simple website? Hence, I am going to use it to create a login system for my own web interface.The framework will create a login system to make my data secure and easily manage of code. I am developing this on version 3.0.2 and this tutorial may not work in later version changes. Here are Simple steps to follow:

  1. Download Codeigniter and unzip it in respective www folder. Thats it. I myself though it would include complex process of modifying PHP extensions, modules and stuff but unzipping the zip installs it. Nothing much complex.
  2. Now for login you need MySQL. Login in into it, create your database you like and create table below.
    CREATE TABLE `users` (
     `id` tinyint(4) NOT NULL AUTO_INCREMENT,
     `username` varchar(10) NOT NULL,
     `password` varchar(100) NOT NULL,
     PRIMARY KEY (`id`)
    ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    
  3. Add a user.
    insert into users (username, password) values ('gman', MD5('password'));
    
  4. Link Codeigniter with MySQL database in application/config/database.php
    $db['default'] = array(
     'dsn' => '',
     'hostname' => 'localhost',
     'username' => 'root',
     'password' => 'password',
     'database' => 'databasename',
    
  5. Change the route from welcome to login in application/config/routes.php
    $route['default_controller'] = "login";
    
  6. the file application/config/autoload.php loads packages, libraries, helpers, languages and drivers by default. The framework is kept minimalistic. Therefore none of them are activated by default. Add the following libraries and helper required for login system.
    $autoload['libraries'] = array('database','session');
    ...
    $autoload['helper'] = array('url');
    
  7. Set the encryption key in application/config/config.php. I had no clue what to keep so I generated it from http://jeffreybarke.net/tools/codeigniter-encryption-key-generator/
    $config['encryption_key'] = 'J6HHz5G5F02ngqX1phtMFDkYvYshgOtC';
    
  8. Configure .htaccess file
    <IfModule mod_rewrite.c>
      RewriteEngine On
      # !IMPORTANT! Set your RewriteBase here and don't forget trailing and leading
      #  slashes.
      # If your page resides at
      #  http://www.example.com/mypage/test1
      # then use
      # RewriteBase /mypage/test1/
      RewriteBase /
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteRule $1 !^(index\.php|img|images|css|js|fonts|fontrobots\.txt)
      RewriteRule ^(.*)$ index.php?/$1 [L]
    </IfModule>
    
    <IfModule !mod_rewrite.c>
      # If we don't have mod_rewrite installed, all 404's
      # can be sent to index.php, and everything works as normal.
      # Submitted by: ElliotHaughin
    
      ErrorDocument 404 /index.php
    </IfModule>
    
  9. Enough Config stuff. Lets get straight to the point yeah! Lets create a User Model by creating User.php as application/models/
    <?php
    Class User extends CI_Model
    {
     function login($username, $password)
     {
       $this -> db -> select('id, username, password');
       $this -> db -> from('users');
       $this -> db -> where('username', $username);
       $this -> db -> where('password', MD5($password));
       $this -> db -> limit(1);
     
       $query = $this -> db -> get();
     
       if($query -> num_rows() == 1)
       {
         return $query->result();
       }
       else
       {
         return false;
       }
     }
    }
    ?>
    
  10. Create a controller for login (application/controllers/Login.php). This controller is just to take you to the login page and not related to login verification. That comes later.
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
     
    class Login extends CI_Controller {
     
     function __construct()
     {
       parent::__construct();
     }
     
     function index()
     {
       $this->load->helper(array('form'));
       $this->load->view('login_view');
     }
     
    }
     
    ?>
    
  11. The html stuff comes in application/views/login_view.php. Use your js from cdn, css in css folder in root and use base_url(); to link to them.
    <!DOCTYPE html>
    <html>
     <head>
       <title>Simple Login with CodeIgniter</title>
     </head>
     <body>
       <h1>Simple Login with CodeIgniter</h1>
       <?php echo validation_errors(); ?>
       <?php echo form_open('verifylogin'); ?>
         <label for="username">Username:</label>
         <input type="text" size="20" id="username" name="username"/>
         <br/>
         <label for="password">Password:</label>
         <input type="password" size="20" id="password" name="password"/>
         <br/>
         <input type="submit" value="Login"/>
       </form>
     </body>
    </html>
    
  12. Now this is the code that I was unable to get my head around. This controller verifies the login. Add the below code in application/controllers/Verifylogin.php
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
     
    class VerifyLogin extends CI_Controller {
     
     function __construct()
     {
       parent::__construct();
       $this->load->model('user','',TRUE);
     }
     
     function index()
     {
       //This method will have the credentials validation
       $this->load->library('form_validation');
     
       $this->form_validation->set_rules('username', 'Username', 'trim|required');
       $this->form_validation->set_rules('password', 'Password', 'trim|required|callback_check_database');
     
       if($this->form_validation->run() == FALSE)
       {
         //Field validation failed.  User redirected to login page
         $this->load->view('login_view');
       }
       else
       {
         //Go to private area
         redirect('home', 'refresh');
       }
     
     }
     
     function check_database($password)
     {
       //Field validation succeeded.  Validate against database
       $username = $this->input->post('username');
     
       //query the database
       $result = $this->user->login($username, $password);
     
       if($result)
       {
         $sess_array = array();
         foreach($result as $row)
         {
           $sess_array = array(
             'id' => $row->id,
             'username' => $row->username
           );
           $login_data = array( 'logged_in' => $sess_array );
           $this->session->set_userdata($login_data);
         }
         return TRUE;
       }
       else
       {
         $this->form_validation->set_message('check_database', 'Invalid username or password');
         return false;
       }
     }
    }
    ?>
    
  13. Create Homepage controller in application/controllers/home.php
    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    
    class Home extends CI_Controller {
     
     
     function index()
     {
       if($this->session->userdata('logged_in'))
       {
         $session_data = $this->session->userdata('logged_in');
         $data['username'] = $session_data['username'];
         $this->load->view('home_view', $data);
       }
       else
       {
    
         //If no session, redirect to login page
         redirect('login', 'refresh');
       }
     }
     
     function logout()
     {
       $this->session->unset_userdata('logged_in');
       session_destroy();
       redirect('home', 'refresh');
     }
     
    }
     
    ?>
    
  14. Finally, add a view of home in application/views/home_view.php
    <!DOCTYPE html>
    <html>
     <head>
       <title>Simple Login with CodeIgniter - Private Area</title>
     </head>
     <body>
       <h1>Home</h1>
       <h2>Welcome <?php echo $username; ?>!</h2>
       <a href="home/logout">Logout</a>
     </body>
    </html>
    
Thats all! Hope this is helpful. Please comment if you face any error.

Comments

Anonymous said…
Thank you helped me a lot, more examples on Codeigniter :)
Lee Davis said…
This script, although educational, isn't functional whatsoever - the main sticking point is the line, $result = $this->user->login($name, $password); (verifylogin.php) where user isn't an object at all and the error messages state, "Message: Undefined property: VerifyLogin::$user" and "Call to a member function login() on a non-object".
Anonymous said…
The sample works just fine. check if in your user model you have the function login defined

Popular posts from this blog

Switching from Notepad++ FTP to Visual Studio Code FTP

jTable to edit and process MySQL table using CodeIgnitor : Part 2

Simple PHP Script to read Tab Delimited File