How to Create User login using codeigniter?

Today I will teach you how to create user login using codeigniter ,Let’s create login controller as below.
With this login we can create a function called as user_login(); that will load our login view. keep in mind, for good programming behavior, we will also include our constructor function, with in that call the parent constructor as well.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -  
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */

        public $data;
 	public function __construct()
	{
            //Core controller constructor
	    parent::__construct();
	    $this->load->model('ektreemodel');
               
				
	}
	
        public function user_login()
	{
		$post = $this->input->post(NULL, TRUE);
		$data = array();
		$username= $this->input->post("txtLoginid");
		$password =$this->input->post("txtPasswd");

		$this->load->library('form_validation');
		$this->form_validation->set_rules('txtLoginid','email','required|valid_email|xss_clean|trim');
		$this->form_validation->set_rules('txtPasswd','Password','required|xss_clean|trim');

		if ($this->form_validation->run() == FALSE)
		{	
		    $this->load->view('demos/login',$this->data);
		}//if
		else
		{  
		
		$userinfo = $this->ektreemodel->validate_user($username,$password);
			//passing data to view
		if($userinfo['error'])
		 {
		 $data['error'] = $userinfo['error'];
		 $this->load->view('demos/login',$this->data);
		 }
		}
    }
}

Once we created our login controller, we can go to the front and create our login view file. Here
we will create a very easy form, using some css styles to look superior. if needed, you can add this view file directly to your project.

<html>
<head>
<title>Login Demo</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/loginstyles.css" />
</head>

<body>   

<span  class="button" id="toggle-login">Log in</span>

<div id="login">
  <div id="triangle"></div>
  <h1>Log in</h1>
 <form method="post" action="user_login" role="form" >
     <?php if($this->session->flashdata('message')) {?>
 <label><?php echo $this->session->flashdata('message');?></label>
<?php }?>
     <input name="txtLoginid" type="email" size="25" id="txtLoginid" placeholder="Enter email" class="form-control" value="<?php echo set_value('txtLoginid');?>" />
     <span style="color:red"><?php echo form_error('txtLoginid');?></span>
    <input name="txtPasswd" type="password" id="txtPasswd" value="<?php echo set_value('txtPasswd');?>" class="form-control" placeholder="Password"/>
    <span style="color:red"><?php echo form_error('txtPasswd');?></span>
    <input type="submit" value="Log in" />
  </form>
</div>
 </body>
</html>
<script type="text/javascript" src="<?php echo base_url();?>scripts/jquery.min.js"></script>
<script>
$('#toggle-login').click(function(){
  $('#login').toggle();
});
</script>

If you observe above, the form action is set to – user_login. This is supercilious that your base_url is set as the following: “http://localhost/demos”. Notice the final slash.
So now, when we submit the login details it will navigate to user_login method. Within this method, we will call our model, and procedure our logic in the model. Let’s do so:

<?php
class Ektreemodel extends CI_Model
{
  
        /**
	* file upload method
	* @access	public
	**/
	
      
 public function validate_user($_username,$_password)
 {
			  
    $where = array("emailid" => $_username, "pass_encryption" => md5($_password));

    $sql = $this->db->where($where);
    $sql = $this->db->get($this->db->dbprefix."ektree_user");
    $rs = $sql->row_array();
				   //checking the array is empty or not
    if(!empty($rs)) 
        {
           //checking the user is admin or not
               if($rs['usertype'] == 'user') 
                    {
                            // store data into session
                            $newdata = array(
                                    'user_id'  => $rs['user_id'],
                                    'usertype'  => $rs['usertype'],
                                    'emailid'  => $rs['emailid'],
                                    'firstname' => $rs['firstname']

                            );	

                            $this->session->set_userdata($newdata);				
                            $this->load->view('demos/view_home');
                    }

         }		
					
     else
             {

                            return array('error' => 'The username or password you entered is incorrect.');	
             }
			 
 }//end validate_user
    
    
    
}
?>

Now in the model we will create a method called validate. In this method we will query our database and get the user details and will return true or false, depending on the outcome. Also, we will use the codeigniter sessions class, to create a user-specific session. Now let’s check the method once.
If the confirmation was unsuccessful, then we need to inform the user that something is wrong.
Let’s add in a message representing the user to enter the valid username and password.
Using codeigniter session flash data we will create a message. Now we will add a parameter to our function in login controller. The evasion message will be null, sense there will be nothing to display, but if error occurs, we call the method with a message
Thanks for reading this article..
Live Demo

READ  Codeigniter advanced search functionality implementation.

4 Comments

  1. Adi March 18, 2015
  2. SIVA SANKAR MOLKA March 24, 2015
  3. J. Moi May 19, 2015
  4. admin May 19, 2015

Leave a Reply