Home

Monday, December 31, 2012

How to Create Login Form in CodeIgniter


Step : 1

Default Libraries

In the file application/config/autoload.php you can configure the default libraries you want to load in all your controllers.  For our case, we’ll load the database and session libraries, since we want to handle user sessions, and also the URL helper for internal link generation

Before Line No : 55  $autoload['libraries'] = array();
After   Line No : 55  $autoload['libraries'] = array('database','session');

Before Line No : 67  $autoload['helper'] = array();
After   Line No : 67  $autoload['helper'] = array('url');

Encryption Key

When you use the session library, you need to set the encryption_key in the file application/config/config.php.

Before Line No : 227 $config['encryption_key'] = '';
After   Line No : 227 $config['encryption_key'] = '90b9aa7e25f80cf4f64e990b78a9fc5e';



Step : 2 Create Controller PHP file name is login.php path:(application/controllers/login.php)

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

class login extends CI_Controller
{  
    public function index()
    {
        $this->load->helper(array('form', 'url'));
        ////////  Form Validation Library Load //////////
        $this->load->library('form_validation');
       
        ///////// Session Library Load //////////////////
        $this->load->library('session');      
       
        ////////// Check Validation Form ////////////////
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('username', 'username', 'required|min_length[3]|max_length[12]|trim');
        $this->form_validation->set_rules('password', 'password', 'required|min_length[2]|md5');
      
        if(!$this->form_validation->run())
        {
            $this->load->view('loginform');
        }
        else
        {          
            ///////// Database Liberary Load //////
            $this->load->database();
           
            ///////// Model Call for Login Check/////
            $this->load->model('login_model');          
           
            ///////////  Authentication Check Here //////////////////
            $result = $this->login_model->login($this->input->post('username'),$this->input->post('password'));
           
            if($result)
            {
                $sess_array = array();
                foreach($result as $row)
                {
                    $sess_array = array('id_users' => $row['id_users'],'username' => $row['username']);
                    $this->session->set_userdata('logged_in', $sess_array);
                }                                              
                redirect('home', 'refresh');
                 return TRUE;                                  
            }else
            {                          
                /////////// If Auth. is fail //////
                $data['message'] = "<font class='error'>Invalid username or password..!!</font>";                              
            }
            $this->load->view('loginform',$data);
        }        
    }  
}
?>


Step : 3 Create Model PHP file name is login_model.php  path:(application/models/login_model.php)

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

class login_model extends CI_Model { 
  
    function login($username,$password)
    {  
        $query = "SELECT * FROM ci_users WHERE username = '".$username."' AND password = '".md5($password)."' LIMIT 1";  
        $sql = $this->db->query($query);      
       
        if($sql -> num_rows() == 1)
        {
            return $sql->result_array();
        }
        else
        {
            return false;
        }          
    }
}
?>


Step : 4 Create View PHP file name is loginform.php  path:(application/views/loginform.php)

loginform.php
==>
<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>

<style>
h1{
    color:#369;
    text-align:center;
}
h3{
    color:#C39;
}
table{
    border:2px solid #0CF;
    border-radius:10px;
}
th{
    text-align:left;
}
input[type="submit"],[type="reset"]
{
    background-color:#000;
    color:#FFF;
}
 .error{
    color:#F00;
}
.success{
    color:#00F;
}
</style>
<?php echo form_open('login'); ?>
       
<h1>Login Form</h1>          
<table cellpadding="10" cellspacing="10" align="center">
<?php
if(@$message)
{
    ?>
        <tR>
            <td colspan="3" align="center"><?php echo $message;?></td>
        </tR>
    <?php
}
?>
    <tR>
        <td colspan="3"><h3>Login information</h3></td>
    </tR>
    <tR>
        <th><label for="username">Username <span class="required">*</span></label></th>
        <td><input type="text" name="username" id="username" value="<?php echo set_value('username'); ?>" class="contact_textfield"/><br><span><?php echo form_error('username'); ?></span></td>                </tR>
    <tR>
        <th><label for="password">Password <span class="required">*</span></label></th>
        <td><input type="password" name="password" class="contact_textfield"/><br><span><?php echo form_error('password'); ?></span></td>                  
    </tR>
  
   <tR>
        <td colspan="2" class="height45"><input type="submit" value="Login"  class="big_btn dark"/> &nbsp; <input type="reset" value="Reset" class="big_btn dark"></td>
    </tR>
  
</table>
     
<?php echo form_close(); ?>


Step : 5 Create Controller PHP file name is home.php  path:(application/controllers/home.php)

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

class Home extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');  
   redirect('home', 'refresh');
 }
}

?>

Step : 6 Create View PHP file name is home.php  path:(application/views/home.php)

home.php
==>
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <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>



Step : 7 Run in Browser Like this http://localhost/codeIgniter/index.php/login



           

No comments:

Post a Comment

rathoddhirendra.blogspot.com-Google pagerank and Worth