Codeigniter Login with Captcha

Codeigniter PHP

Dear friends,

Here we are going to discuss about codeigniter login form with CAPTCHA .

CAPTCHA is a challenge – response test for users to determine whether the user is a human or machine. For secure authentication many web sites use CAPTCHA in different purpose like login,registration etc. CAPTCHAs are in the form of images containing letters. The user need to insert the series of letters shown in the image into given input field.

 

Friends please follow below steps to create a login with CAPTCHA in codeigniter web application.

Step 1: Controller

create a new controller called Authenctication.php in your controller directory of your codeigniter application.


1
2

3

4

5

6
7

8

9

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144

class Authentication extends CI_controller { 
    function __construct() 
    { 
         parent::__construct(); 

		$this->load->library(['form_validation','session']);
		$this->load->database();
		$this->load->helper(['captcha']);
    }
    public function index()
    {
	redirect('authentication/login');
     }
     public function login()
     {
		$data	 =	array();
		if(isset($_POST['submit']))
		{
			$this->form_validation->set_rules('username','Username',
'required');
			$this->form_validation->set_rules('password','Password',
'required|min_length[8]|max_length[16]');
			$this->form_validation->set_rules('captcha','Access Code',
'required');
			if($this->form_validation->run() ==  TRUE)
			{
			       // success
                               //catcha checking 
	                       $captcha         = $this->input->post('captcha');
	                       $captcha_session = $this->session->userdata('captcha');
	                       if ($captcha == $captcha_session ) 
	                       {
	                            // true - captcha matches

					$username 		=	
$_POST['username'];
					$user_username 		=	$this->db->
get_where('login',['login_username' => $username ])->row_array();

					if(isset($user_username['login_id']) && 
$user_username['login_password'] != '')
					{
						//true, check password
						$password 		=	
$_POST['password'];
						
						if(isset($password) &&  password_verify
($password,$user_username['login_password']))
						{
							//redirect to home
                                                        redirect('authentication/home');
						}
						else
						{
						   $this->session->set_flashdata('login'
,'Invalid Username or Password');
						}
							
					}
					else
					{ 
					         //failed to login
						$this->session->set_flashdata('login',
'Invalid Username or Password');
					}
						
				}
				else
				{
					//captcha not matches
						$this->session->set_flashdata('login',
'Incorrect Access Code');
				}
	 		}

		}

		/*  CAPTCHA  STARTS */
		if(!is_dir('./assets/captch_img/'))
		{
			mkdir('./assets/captch_img/','0777',true);
		}

		$config 			= array(
                       'img_url' 			=> base_url() . 'assets/
captch_img/',
                       'img_path' 			=> 'assets/captch_img/',
                       'img_height' 		=> 45,
                       'word_length' 		=> 5,
                       'img_width' 		=> '200',
                       'font_size' 		=> 10
                );

                $captcha_new  = create_captcha($config);
                unset($_SESSION['captcha']);
                $this->session->set_userdata('captcha', $captcha_new['word']);
                $data['captchaImage'] = $captcha_new['image'];
		/* CAPTCHA ENDS */


		$this->load->view(login,$data);
	}


	public function captcha_refresh()
        {
           $config = array(
            'img_url'     => base_url() . 'assets/captch_img/',
            'img_path'    => 'assets/captch_img/',
            'img_height'  => 45,
            'word_length' => 5,
            'img_width'   => '200',
            'font_size'   => 10
           );
        $captcha_new = create_captcha($config);
        unset($_SESSION['captcha']);
        $this->session->set_userdata('captcha', $captcha_new['word']);
        echo $captcha_new['image'];
    }
    public function home()
    {
          $this->load->view('home');
    }
        public function signout()
	{
		
		session_destroy();
		unset($_SESSION);
		$data		=	array();
		
			

		/*  CAPTCHA  STARTS */

		$config 			= array(
                       'img_url' 		=> base_url() . 'assets/captch_img/',
                       'img_path' 		=> 'assets/captch_img/',
                       'img_height' 		=> 45,
                       'word_length' 		=> 5,
                       'img_width' 		=> '200',
                       'font_size' 		=> 10
                );

                $captcha_new  = create_captcha($config);
                unset($_SESSION['captcha']);
                $this->session->set_userdata('captcha', $captcha_new['word']);
                $data['captchaImg'] = $captcha_new['image'];
		/* CAPTCHA ENDS */

		$this->load->view(login,$data);
	}
}

?>

Step 2: Database

Create a login table and insert data to  MySQL database.

--
-- Table structure for table `login`
--

CREATE TABLE IF NOT EXISTS `login` (
  `login_id` int(1) NOT NULL,
  `login_username` varchar(200) NOT NULL,
  `login_password` varchar(250) NOT NULL,
  `login_status` int(1) NOT NULL,
  PRIMARY KEY (login_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `csv`
--

INSERT INTO `login` (`login_id`, `name`, `login_username`, `login_password`, 
`login_status`) VALUES
(1, 'admin', '$2y$08$7v6Dm3RTncuqYFoZW4U20eui6mKwBBnqwtsrvbAt9LuD0GvixmsOy', 
1);

--
-- Indexes for dumped tables
--

Step 3: View

Create a view file called login.php in application/views/. Then Copy and paste the code to your view file and  save it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<html>
 <head>
 <title>|LOGIN |</title> 
 <!-- Latest compiled and minified CSS -->  
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
bootstrap.min.css">
 <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
 <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
  <style type="text/css">
      .top { } 
   </style>
 </head>
 <body>
      <div class="">
          <div class="row">
              Login
          </div>
          <div class="col-md-4">
              <h2>Login</h2>
              <?php if(issst($login)) echo '<p>'.$login.'</p>'; ?>
              <form method="post">
                 <div class="form-group">
                     <input type="text" class="form-control form-control-lg"
 placeholder="Username" name="username" id="username" required>
                 </div>
                 <div class="form-group">
                     <input type="password" class="form-control form-control-lg"
 placeholder="password" name="password" id="password" required>
                 </div>
                 <div class="form-group" style="margin-left: 30px;">
                    <p>Access Code</p>
                    <span id="captchaImage" ><?php if(isset($captchaImage)) 
echo $captchaImage; ?> </span>
                    <a class="btn loadCaptcha" href="javascript:void(0);" title="Refresh Captcha Access code" >
<i class="glyphicon glyphicon-chevron-right"></i></a>
                 </div>
                 <div class="form-group">
                     <input type="text" class="form-control form-control-lg"
 placeholder="Captcha" name="captcha" id="password" captcha>
                 </div> 
                 <div class="form-group">
                      <input type="submit" name="submit" value="SUBMIT"/>
                 </div>
              </form>
          </div> 
         <script>
            $(document).ready(function(){
                $('.loadCaptcha').on('click', function(){
                  $.get('<?php echo site_url("authentication/captcha_refresh"); ?>', function(data){
                         $('#captchaImage').html(data);
                   });
                });
           }); 
         </script> 
      </div> 
  </body>
</html> 

 

Home page for after successful login.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
 <head>
 <title>|Home|</title> 
 <!-- Latest compiled and minified CSS -->  
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
bootstrap.min.css">
 <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
 <!-- Latest compiled JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
  <style type="text/css">
      .top { } 
   </style>
 </head>
 <body>
      <div class="container">
        <a href="<?php echo site_url('authentication/signout'); ?>">Logout</a> 
      </div> 
  </body>
</html> 

 

Step 4: Open browser and type url to view the site.

Leave a Reply

Your email address will not be published. Required fields are marked *