Showing posts with label recaptcha. Show all posts
Showing posts with label recaptcha. Show all posts

Tuesday, 13 October 2020

How to Implement Google reCaptcha in Codeigniter



This post will covered How to add Google re Captcha in Codeigniter application or in another word How to validate Codeigniter Form data by using Google reCaptcha validation. This is simple post on Integration of Google reCaptcha in PHP Codeigniter framework. In this tutorial, we will step by step describe you implementation of Google reCaptcha in Codeingniter application.

Now in your mind one question will arise why need to Add Google reCaptcha in our Form. So by using this Google reCaptcha, we can reduce form spam entry and it will stop storing spam data in our web application.

What is reCaptcha?


reCaptcha is one of the free services which has been provided by Google and it will protect our online web application from the spam data and abuse. It has been used some advanced risk analysis techniques which will be tells that particular user is humans or bots which has fill form data. So, it is mainly used for reduce spamming in our website.

What are benifits of using reCaptcha


There are several benifits of Google reCaptcha which you can find below.

  • It will protect our website registration form from spamming registration.
  • It will prevent from spam comments
  • It will secured our Online Shopping
  • It will protect our Email Account

So there are many other benifits of adding Google reCaptcha in our Codeigniter website. But now below you can find step by step process for integrate Google recaptcha in Codeigniter framework.




1. Get Google reCaptcha Site Key and Secret Key


In first step we want to get the Google recaptcha Site key and Secret key. So first we have to login into our Google account and then after https://www.google.com/recaptcha/admin/create and register your domain name in which website you want to add. So in below you image you can find data like label, reCAPTCHA type and domain name field. After filling this details, you have to click on submit button.



Once you have click on submit button, then you can get Google reCaptcha site key and secret key which you can see in below image. So you have to copy both key and store in safe place. We will use both key in Codeigniter for integrate Google reCaptcha with Codeigniter framework.



2. Define Base Url in Codeigniter


Before starting coding in Codeigniter framework, we have to first define base url of Codeigniter application. For define base url, we have to open application/config/ config.php and under that file you have define base url at $config['base_url'] in this variable.


$config['base_url'] = 'http://localhost/tutorial/codeigniter/';


3. Make Database Connection


For making MySql Database connection in Codeigniter framework, we have to open application/config/database.php file and under this file we have to define Mysql Database configuration.


$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
	'dsn'	=> '',
	'hostname' => 'localhost',
	'username' => 'root',
	'password' => '',
	'database' => 'testing',
	'dbdriver' => 'mysqli',
	'dbprefix' => '',
	'pconnect' => FALSE,
	'db_debug' => (ENVIRONMENT !== 'production'),
	'cache_on' => FALSE,
	'cachedir' => '',
	'char_set' => 'utf8',
	'dbcollat' => 'utf8_general_ci',
	'swap_pre' => '',
	'encrypt' => FALSE,
	'compress' => FALSE,
	'stricton' => FALSE,
	'failover' => array(),
	'save_queries' => TRUE
);


4. Make Table in Mysql Database


After making Mysql database connection in Codeigniter framework, next we want to create table in Mysql database. So for create table in Mysql database, we have to run following SQL script in phpMyAdmin and it will make sample_data table will create in Mysql database.


--
-- Table structure for table `sample_data`
--

CREATE TABLE `sample_data` (
  `id` int(10) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `age` varchar(30) NOT NULL,
  `gender` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `sample_data`
--
ALTER TABLE `sample_data`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_data`
--
ALTER TABLE `sample_data`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;



5. Create Controller in Codeigniter


Codeigniter is a MVC model based framework and under this framework Controllers class has been used for handle http request. So for handle Google reCaptcha validation here we have create application/controllers/Captcha.php file and under this class file we have make following method.

__construct() - This magic method will execute code when object of this class has been created and it will load session library and captcha model class under this class. So we can use both class mehtod under this class.

index() - This is root method of this class and it will display views/captcha.php file html content on web page.

validate() - This method has been received form data from client side and under this method firs it has been check g-recaptcha-response variable value has been set or not. If this variable value is set then only it will execute other code. This variable has been generated by Google reCaptcha site key. And then after for check at server side it has use Secret key and send request reCaptcha api for get response regarding user has give proper answer or not. If from reCaptcha api success variable value has been received that means user has pass google recaptcha validation and then after data will be inserted into Mysql database. So here without Google reCaptcha validation data will not be insert into our system.

application/controllers/Captcha.php

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

class Captcha extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
		$this->load->model('captcha_model');
	}

	function index()
	{
		$this->load->view('captcha');
	}

	function validate()
	{
		$captcha_response = trim($this->input->post('g-recaptcha-response'));

		if($captcha_response != '')
		{
			$keySecret = '6LefzNYZAAAAABWAiYy2_X2OiBSZkXdT7K-OoaKW';

			$check = array(
				'secret'		=>	$keySecret,
				'response'		=>	$this->input->post('g-recaptcha-response')
			);

			$startProcess = curl_init();

			curl_setopt($startProcess, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");

			curl_setopt($startProcess, CURLOPT_POST, true);

			curl_setopt($startProcess, CURLOPT_POSTFIELDS, http_build_query($check));

			curl_setopt($startProcess, CURLOPT_SSL_VERIFYPEER, false);

			curl_setopt($startProcess, CURLOPT_RETURNTRANSFER, true);

			$receiveData = curl_exec($startProcess);

			$finalResponse = json_decode($receiveData, true);

			if($finalResponse['success'])
			{
				$storeData = array(
					'first_name'	=>	$this->input->post('first_name'),
					'last_name'		=>	$this->input->post('last_name'),
					'age'			=>	$this->input->post('age'),
					'gender'		=>	$this->input->post('gender')
				);

				$this->captcha_model->insert($storeData);

				$this->session->set_flashdata('success_message', 'Data Stored Successfully');

				redirect('captcha');
			}
			else
			{
				$this->session->set_flashdata('message', 'Validation Fail Try Again');
				redirect('captcha');
			}
		}
		else
		{
			$this->session->set_flashdata('message', 'Validation Fail Try Again');

			redirect('captcha');
		}
	}

}

?>


6. Create Models class in Codeigniter


In Codeigniter models class has been used for perform database related operation and models chass has been created in application/models directory. In this tutorial, we have create Captcha_models.php class file and under this file we have make insert() method which has been used for insert data into Mysql table.

application/models/Captcha_models.php

<?php

class Captcha_model extends CI_Model
{
	function insert($data)
	{
		$this->db->insert('sample_data', $data);
	}
}


7. Create Views file in Codeigniter


Views file has been used for display HTML output in brwoser under this Codeigniter framework and here we have create application/views/captcha.php file. Under this file we have make one html form for get data from user table and for create Google reCaptcha under this form we have create one division tag with class=g-recaptcha and at under this tag we have add data-sitekey and under this attirbute value we have to define Google reCaptcha site key. So by define this site key it will generate Google reCaptcha wiget under this form.

application/views/captcha.php

<html>
<head>
    <title>How to Implement Google reCaptcha in Codeigniter</title>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
    <div class="container box">
        <br />
        <h2 align="center"><b>How to Implement Google reCaptcha in Codeigniter</b></h2>
        <br />
        <div class="panel panel-default">
            <div class="panel-heading">Fill Form Data</div>
            <div class="panel-body">
                <?php
                if($this->session->flashdata('message'))
                {
                ?>
                    <div class="alert alert-danger">
                        <?php
                        echo $this->session->flashdata('message');
                        ?>
                    </div>
                <?php
                }

                if($this->session->flashdata('success_message'))
                {
                ?>
                    <div class="alert alert-success">
                        <?php
                        echo $this->session->flashdata('success_message');
                        ?>
                    </div>
                <?php
                }
                ?>
                <form method="post" action="<?php echo base_url(); ?>captcha/validate">
                    <div class="form-group">
                        <label>First Name</label>
                        <input type="text" name="first_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Last Name</label>
                        <input type="text" name="last_name" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Age</label>
                        <input type="text" name="age" class="form-control" />
                    </div>
                    <div class="form-group">
                        <label>Gender</label>
                        <input type="text" name="gender" class="form-control" />
                    </div>
                    <div class="form-group">
                        <div class="g-recaptcha" data-sitekey="6LefzNYZAAAAAIeoFhVYj3T5BoCEo1Yja5DvCRxP"></div>
                    </div>
                    <div class="form-group">
                        <input type="submit" name="send" class="btn btn-success" value="Send" />
                    </div>
                </form>
            </div>
        </div>        
    </div>
</body>
</html>


So, this is complete step by step process for integrate Google reCaptcha under this Codeigniter application and reduce spam entry in your website. This is because without pass Google reCaptcha validation, data will not be entered into our database. So it will reduce spam attack in our website. If you have any query then you can ask in comment box we will reply on your comment regarding your query.

Wednesday, 11 September 2019

PHP Form with Google reCaptcha



If you not know how to add Google reCaptcha in PHP form, then you have come on right place. Because in this post you can find solution of How to integrate Google reCaptcha in PHP form and here you can also find how to validate PHP form with Google reCaptcha by using Ajax jQuery.

Form data has been validate with Google reCaptcha is required because we all know spamming is one of very common problem which has been faced on web. Every Website owner prevent their website from invalid spam traffic or spam comment.

Before programmer has used random captcha code for prevent spamming or bots filled in their website form. But this is old method and now most of the web application has been used Google reCAPTCHA, for verify that form input field has been filled by any human. Google reCAPTCHA is very simple to verify that he is user. User can verify just in single click for that they are not a robot.

Below you can find step by step guide for How to build PHP spam free form by using Google reCaptcha.



Step 1: Get Google reCaptcha API Key


For get Google reCaptcha API key, you first have Google account. If you have google account, then login into your Google account and visit this website https://www.google.com/recaptcha/admin.





Once you have visit above link then, you can see above image web page. Here you have to define label name, domain name in which you want to integrate Google reCaptcha and click on submit button. Here we want to use in localhost also so we have include localhost in domain list also. And lastly click on submit button, then you can get API key, which you can see below.









Add Google reCaptcha API key in your web page


In this tutorial, we will create our HTML form in index.php file. So, in this file first we need to add reCAPTCHA javascript library in our HTML code.


<script src="https://www.google.com/recaptcha/api.js" async defer></script>


After this we want to add following HTML code for generate Google reCAPTCHA widget in form.


<div class="g-recaptcha" data-sitekey="6Ldv2bcUAAAAAFeYuQAQWH7I_BVv2_2_fedg2Fpp"></div>


Here in data-sitekey value, we have to add site key which we have get from Google reCAPTCHA api key. Once you have add this code and refresh web page then Google reCaptcha widget will be created in your web page. Below you can source code of index.php file




index.php

<html>  
    <head>  
        <title>How to Implement Google reCaptcha in PHP Form</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>  
    <body>  
        <div class="container" style="width: 600px">
   <br />
   
   <h3 align="center">How to Implement Google reCaptcha in PHP Form</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register Form</div>
    <div class="panel-body">
     
     <form metod="post" id="captcha_form">
      <div class="form-group">
       <div class="row">
        <div class="col-md-6">
         <label>First Name <span class="text-danger">*</span></label>
         <input type="text" name="first_name" id="first_name" class="form-control" />
         <span id="first_name_error" class="text-danger"></span>
        </div>
        <div class="col-md-6">
         <label>Last Name <span class="text-danger">*</span></label>
         <input type="text" name="last_name" id="last_name" class="form-control" />
         <span id="last_name_error" class="text-danger"></span>
        </div>
       </div>
      </div>
      <div class="form-group">
       <label>Email Address <span class="text-danger">*</span></label>
       <input type="text" name="email" id="email" class="form-control" />
       <span id="email_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <label>Password <span class="text-danger">*</span></label>
       <input type="password" name="password" id="password" class="form-control" />
       <span id="password_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <div class="g-recaptcha" data-sitekey="6Ldv2bcUAAAAAFeYuQAQWH7I_BVv2_2_vvmn2Fpp"></div>
       <span id="captcha_error" class="text-danger"></span>
      </div>
      <div class="form-group">
       <input type="submit" name="register" id="register" class="btn btn-info" value="Register" />
      </div>
     </form>
     
    </div>
   </div>
  </div>
    </body>  
</html>

<script>
$(document).ready(function(){

 $('#captcha_form').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"process_data.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#register').attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#register').attr('disabled', false);
    if(data.success)
    {
     $('#captcha_form')[0].reset();
     $('#first_name_error').text('');
     $('#last_name_error').text('');
     $('#email_error').text('');
     $('#password_error').text('');
     $('#captcha_error').text('');
     grecaptcha.reset();
     alert('Form Successfully validated');
    }
    else
    {
     $('#first_name_error').text(data.first_name_error);
     $('#last_name_error').text(data.last_name_error);
     $('#email_error').text(data.email_error);
     $('#password_error').text(data.password_error);
     $('#captcha_error').text(data.captcha_error);
    }
   }
  })
 });

});
</script>


Validate User Response at Server side


After this we need to validate user response at server side, for this we have to process_data.php file, in which recaptcha response data will be received using Ajax. When user submit form, then reCAPTCHA widget response has been received at process_data.php using Ajax. Here we need to verify response by following php script.


if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = '6Ldv2bcUAAAAAFXUKdLW_qljFd9FpxNguf06DHhp';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }


Here in secret key variable, we need to define secret key which we have get from Google reCaptcha website. Here you need to define your secret key which you have get at the time of generating Google reCAPTCHA API key.

For validate user response here we have send request to Google reCaptcha API url for check user response is proper or not using file_get_contents() function. Below you can find complete PHP script for validate form data with Google recaptcha response also.

process_data.php


<?php

//process_data.php

if(isset($_POST["first_name"]))
{
 $first_name = '';
 $last_name = '';
 $email = '';
 $password = '';

 $first_name_error = '';
 $last_name_error = '';
 $email_error = '';
 $password_error = '';
 $captcha_error = '';

 if(empty($_POST["first_name"]))
 {
  $first_name_error = 'First name is required';
 }
 else
 {
  $first_name = $_POST["first_name"];
 }

 if(empty($_POST["last_name"]))
 {
  $last_name_error = 'Last name is required';
 }
 else
 {
  $last_name = $_POST["last_name"];
 }
 if(empty($_POST["email"]))
 {
  $email_error = 'Email is required';
 }
 else
 {
  if(!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL))
  {
   $email_error = 'Invalid Email';
  }
  else
  {
   $email = $_POST["email"];
  }
 }

 if(empty($_POST["password"]))
 {
  $password_error = 'Password is required';
 }
 else
 {
  $password = $_POST["password"];
 }

 if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  $secret_key = '6Ldv2bcUAAAAAFXUKdLW_qljFd9FpxNguf06DHhp';

  $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret_key.'&response='.$_POST['g-recaptcha-response']);

  $response_data = json_decode($response);

  if(!$response_data->success)
  {
   $captcha_error = 'Captcha verification failed';
  }
 }

 if($first_name_error == '' && $last_name_error == '' && $email_error == '' && $password_error == '' && $captcha_error == '')
 {
  $data = array(
   'success'  => true
  );
 }
 else
 {
  $data = array(
   'first_name_error' => $first_name_error,
   'last_name_error' => $last_name_error,
   'email_error'  => $email_error,
   'password_error' => $password_error,
   'captcha_error'  => $captcha_error
  );
 }

 echo json_encode($data);
}

?>


So, this was the complete step by step process for using Google reCaptcha with PHP and validate response using Ajax with PHP. We hope you can understan how to integrate Google reCAPTCHA checkbox using PHP.