Create Login System with CodeIgniter MVC Model

Tuesday, October 27, 2015
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.

26 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

Anonymous said...

If the passwords are SHA1 hashed, do I replace MD5 with SHA1 or?

Dhananjay said...

Thanks for sharing such a nice information with us on Code Igniter and MVC. Very useful lines and to the point.Appreciate your skill , keep sharing such wonderful information.
Code Igniter Interview Questions Answers
Code Igniter Advanced Interview Questions Answers
Code Igniter Basic Interview Questions Answers
Hooks in CodeIgniter

infocampusbangalore said...

I was able to find good info from your blog posts.
UI Development Training in Bangalore
Reactjs Traning in Bangalore

sangeethalimra said...

Your blog is very nice and we hope you are providing more information in future times.
Ecommerce Web Development Company Bangalore | Mobile App Development Company In Bangalore | Mobile App Development Company Bangalore | Digital Marketing Services In Bangalore




Anonymous said...

Great information
Mobile App Development Company Bangalore
Mobile App Development in Bangalore
Mobile App Development Services Company in Bangalore

aravind said...

A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
DevOps Training in Chennai

DevOps Online Training in Chennai

DevOps Training in Bangalore

DevOps Training in Hyderabad

DevOps Training in Coimbatore

DevOps Training

DevOps Online Training

aravind said...

This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.Thank you for taking the time to provide us with your valuable information.
DevOps Training in Chennai

DevOps Online Training in Chennai

DevOps Training in Bangalore

DevOps Training in Hyderabad

DevOps Training in Coimbatore

DevOps Training

DevOps Online Training

lavanya said...

I'm really enjoying the design and layout of your website. It's a very easy on the eyes which makes it much more pleasant for me to come here and visit more often.keep it up!!

Java training in Chennai

Java Online training in Chennai

Java Course in Chennai

Best JAVA Training Institutes in Chennai

Java training in Bangalore

Java training in Hyderabad

Java Training in Coimbatore

Java Training

Java Online Training

lavanya said...

What is Scala used for? A lot of things, ranging from machine learning to web apps. As a high-level general purpose language, Scala boasts an extensive range of possible applications. Scala allows developers to make good use of standard JVM features and Java libraries.
Java training in Bangalore

Java training in Hyderabad

Java Training in Coimbatore

Java Training

Java Online Training



surya said...

thank you for the information. it is very useful and informative


angular js training in chennai

angular training in chennai

angular js online training in chennai

angular js training in bangalore

angular js training in hyderabad

angular js training in coimbatore

angular js training

angular js online training

lavanya said...

Activities, like writing APIs, creating libraries, and working with system components without user interfaces or even systems of scientific programming, are also included in the backend. ... It is also used as backend language. Java: Java is one of the most popular and widely used programming language and platform.
Java Training in Chennai

Java Training in Bangalore

Java Training in Hyderabad

Java Training in Coimbatore

Java Training

anand said...

great post
Software Testing Training in Chennai | Certification | Online
Courses

Software Testing Training in Chennai

Software Testing Online Training in Chennai

Software Testing Courses in Chennai

Software Testing Training in Bangalore

Software Testing Training in Hyderabad

Software Testing Training in Coimbatore

Software Testing Training

Software Testing Online Training

Rashika said...

Well Said, you have furnished the right information that will be useful to anyone at all time. Thanks for sharing your Ideas.
Digital Marketing Training in Chennai

Digital Marketing Course in Chennai

SEO Training in Chennai

Digital Marketing Training in Bangalore

Digital Marketing Training in Hyderabad

Digital Marketing Training in Coimbatore

Digital Marketing Training

Digital Marketing Course

Digital Marketing Online Training

radhika said...

Nice article i was really impressed by seeing this article, it was very interesting and it is very useful for me.This is incredible,I feel really happy to have seen your webpage.I gained many unknown information, the way you have clearly explained is really fantastic.keep posting such useful information.



AWS Course in Chennai

AWS Course in Bangalore

AWS Course in Hyderabad

AWS Course in Coimbatore

AWS Course

AWS Certification Course

AWS Certification Training

AWS Online Training

AWS Training

vivekvedha said...

Thanks for sharing such a nice information with us on Code Igniter and MVC. Very useful lines and to the point.
acte reviews

acte velachery reviews

acte tambaram reviews

acte anna nagar reviews

acte porur reviews

acte omr reviews

acte chennai reviews

acte student reviews

vivekvedha said...

Thanks for sharing such a nice information with us.
acte reviews

acte velachery reviews

acte tambaram reviews

acte anna nagar reviews

acte porur reviews

acte omr reviews

acte chennai reviews

acte student reviews

swaroop said...

Really it as an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing.

Web Designing Training in Bangalore

Web Designing Course in Bangalore

Web Designing Training in Hyderabad

Web Designing Course in Hyderabad

Web Designing Training in Coimbatore

Web Designing Training

Web Designing Online Training

rocky said...

Thank you for taking the time to provide us with your valuable information.It’s great to come across a blog every once in a while that isn’t the same out of date rehashed material. Fantastic read.
python training in chennai

python course in chennai

python online training in chennai

python training in bangalore

python training in hyderabad

python online training

python training

python flask training

python flask online training

python training in coimbatore

surya said...

thank you for the information



angular js course in chennai

angular course in chennai

angular js online course in chennai

angular js course in bangalore

angular js course in hyderabad

angular js course in coimbatore

angular js course

angular js online course





Revathi said...

You may be keen to become an Android Developer, because the experience of developing Android apps is particularly satisfying. First up, it's cheaper to develop apps for Android. There's no annual fee unlike the Apple platform, which charges you a set fee each year. Also, the Software Development Kit, or SDK, is free.thanks!!

Android Training in Chennai

Android Online Training in Chennai

Android Training in Bangalore

Android Training in Hyderabad

Android Training in Coimbatore

Android Training

Android Online Training


sanjay said...

This blog really pushed to explore more information. Thanks for sharing.
Cyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course |
CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

shiva said...


Great analysis, very useful
| Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course

haseeb said...

If you're new to cybersecurity, you may start out in an entry-level IT role, such as a help desk technician, network administrator, or software .How To Start Cyber Security Career From Scratch