Tuesday, 11 October 2016

CodeIgniter Simple Login Form With Sessions



Hello friends in this tutorial we are going to discuss how to make simple login form with sessions in codeigniter framework. In this tutorial we will make simple login form with session by using Codeigniter framework. In codeigniter framework creating of sessions is different than simple php. We will discuss how to create session for login into system in codeigniter framework. Here we will discuss how can we use model view controller coding style for validate user information and if user has enter right login information and then create simple session variable in codeigniter framework. Here system is working on model view controller coding style, that means here system has received login data from view and from view it has been send to contoller and then after controller has send that data to models for validate data are proper or not, then after model send back result to controller and controller send back result to view. This way login system are work in codeigniter framework. This is my simple codeginiter application for login system.




Source Code

 

 





autoload.php

 <?php  
 $autoload['libraries'] = array('database', 'session');   
 //For Load Session Library in this application  
 ?>  

config.php


 <?php  
 $config['encryption_key'] = 'xRUqKhsoZ5qV6y3kqARFJFdPqJvp7X2z';  
 // For encrypt session data by using encryption class  
 ?>  

Table: users


 --  
 -- Table structure for table `users`  
 --  
 CREATE TABLE IF NOT EXISTS `users` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `username` varchar(250) NOT NULL,  
  `password` varchar(250) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;  
 --  
 -- Dumping data for table `users`  
 --  
 INSERT INTO `users` (`id`, `username`, `password`) VALUES  
 (1, 'admin', 'admin');  

Controllers - main.php


 <?php  
 defined('BASEPATH') OR exit('No direct script access allowed');  
 class Main extends CI_Controller {  
      //functions  
      function login()  
      {  
           //http://localhost/tutorial/codeigniter/main/login  
           $data['title'] = 'CodeIgniter Simple Login Form With Sessions';  
           $this->load->view("login", $data);  
      }  
      function login_validation()  
      {  
           $this->load->library('form_validation');  
           $this->form_validation->set_rules('username', 'Username', 'required');  
           $this->form_validation->set_rules('password', 'Password', 'required');  
           if($this->form_validation->run())  
           {  
                //true  
                $username = $this->input->post('username');  
                $password = $this->input->post('password');  
                //model function  
                $this->load->model('main_model');  
                if($this->main_model->can_login($username, $password))  
                {  
                     $session_data = array(  
                          'username'     =>     $username  
                     );  
                     $this->session->set_userdata($session_data);  
                     redirect(base_url() . 'main/enter');  
                }  
                else  
                {  
                     $this->session->set_flashdata('error', 'Invalid Username and Password');  
                     redirect(base_url() . 'main/login');  
                }  
           }  
           else  
           {  
                //false  
                $this->login();  
           }  
      }  
      function enter(){  
           if($this->session->userdata('username') != '')  
           {  
                echo '<h2>Welcome - '.$this->session->userdata('username').'</h2>';  
                echo '<label><a href="'.base_url

().'main/logout">Logout</a></label>';  
           }  
           else  
           {  
                redirect(base_url() . 'main/login');  
           }  
      }  
      function logout()  
      {  
           $this->session->unset_userdata('username');  
           redirect(base_url() . 'main/login');  
      }  
 }  

Models - main_model.php


 <?php  
 class Main_model extends CI_Model  
 {  
      function can_login($username, $password)  
      {  
           $this->db->where('username', $username);  
           $this->db->where('password', $password);  
           $query = $this->db->get('users');  
           //SELECT * FROM users WHERE username = '$username' AND password = '$password'  
           if($query->num_rows() > 0)  
           {  
                return true;  
           }  
           else  
           {  
                return false;       
           }  
      }  
 }  

Views - login.php


 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Webslesson | <?php echo $title; ?></title>  
      <link rel="stylesheet" 

href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />  
 </head>  
 <body>  
      <div class="container">  
           <br /><br /><br />  
           <form method="post" action="<?php echo base_url(); ?>main/login_validation">  
                <div class="form-group">  
                     <label>Enter Username</label>  
                     <input type="text" name="username" class="form-control" />  
                     <span class="text-danger"><?php echo form_error('username'); ?

></span>                 
                </div>  
                <div class="form-group">  
                     <label>Enter Password</label>  
                     <input type="password" name="password" class="form-control" />  
                     <span class="text-danger"><?php echo form_error('password'); ?

></span>  
                </div>  
                <div class="form-group">  
                     <input type="submit" name="insert" value="Login" class="btn btn-info" />  
                     <?php  
                          echo '<label class="text-danger">'.$this->session->flashdata

("error").'</label>';  
                     ?>  
                </div>  
           </form>  
      </div>  
 </body>  
 </html>  

26 comments:

  1. how if the password hash to md5 during registration. howc to intend to retrive the password when login.

    ReplyDelete
    Replies
    1. Hello Bryan, you will never check the real password. let's say your pw is "123"
      let's hash... now it's "abc", this is what we store. next time you login, you will enter "123" and... yes, thats the point :)

      Delete
    2. You follow code in main_model.php

      function can_login($username,$password){
      $this->db->where('username',$username);
      $this->db->where('password',md5($password));
      $query = $this->db->get('users');
      if($query->num_rows() > 0){
      return true;
      }else {
      return false;
      }

      }

      Delete
    3. You follow code in main_model.php

      function can_login($username,$password){
      $this->db->where('username',$username);
      $this->db->where('password',md5($password));
      $query = $this->db->get('users');
      if($query->num_rows() > 0){
      return true;
      }else {
      return false;
      }

      }

      Delete
  2. when i type wrong user name and password then it shows error
    Call to undefined function form_error() in C:\xampp\htdocs\Suneel_Training\application\views\login.php on line 16

    ReplyDelete
  3. very usefull article
    thnx a lot

    ReplyDelete
  4. can you plz avail the url path of this program. I compiled it as localhost/projectname/main.php.
    but it says
    The requested URL /crudprofile/main.php was not found on this server.

    ReplyDelete
  5. plz comment the URL path of this project

    ReplyDelete
  6. here anybody having source code for user and admin session management system its for my learning purpose
    reach me on : aksitechdev@gmail.com
    TELEGRAM ---- t.me/aksitech

    ReplyDelete
  7. there is an error when loading. 404 Page Not Found...

    ReplyDelete
  8. application\config\routes.php
    change your routes.php like this..

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

    ReplyDelete
  9. error 'The Encrypt library requires the Mcrypt extension'

    ReplyDelete
    Replies
    1. change this code
      from -> $this->load->library('encrypt');
      to -> $this->load->library('encryption');

      hopefully help u

      Delete
  10. i keep losing my data session after i redirect to the page

    ReplyDelete
  11. i am getting a problem saying base_url is not defined

    ReplyDelete
  12. Hi, Can you send me a code?

    ReplyDelete
  13. plz comment the URL path of this project

    ReplyDelete