How to Add Google CAPTCHA in Registration Form in PHP

Add Google Captcha to the registration form in PHP

In this tutorial, We will learn How to integrate Google Captcha in PHP form. Registration form data have been validated with Google Captcha is required, which is used for preventing spam or bots filled in their website form. Google CAPTCHA is very simple to verify that he is human not a bot. The Users can verify just in a single click for that they are not a robot.

Step by step guide for How to add Google Captcha in registration form

How to get google site key and secret key?

To get Google Captcha API Key, first you have a Google account. If you have a Google account, then login into your Google account and visit the Google reCaptcha official link.  https://www.google.com/recaptcha/admin.

Fill all the details like. Label, reCaptcha type, Enter your domain name in which you want to integrate Google reCaptcha, Click on the accept reCaptcha term and condition and click on the submit button.

add Google Captcha in registration form
integrate Google reCaptcha

Once you click on the submit button you will get your site key and secret key.

Google site key and secret key.

Add the below Google reCaptcha v2 API key in your web page in the header section.

Google reCaptcha API

We will design our registration form in the index.php file. So, in index file first we need to add the below the google reCAPTCHA v2 javascript library in the header section.

reCAPTCHA

Database Script

-- phpMyAdmin SQL Dump
-- version 4.9.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 29, 2021 at 11:41 AM
-- Server version: 10.4.10-MariaDB
-- PHP Version: 7.3.12

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `recaptcha`
--

-- --------------------------------------------------------

--
-- Table structure for table `userregisteration`
--

DROP TABLE IF EXISTS `userregisteration`;
CREATE TABLE IF NOT EXISTS `userregisteration` (
  `userID` int(11) NOT NULL AUTO_INCREMENT,
  `fullName` varchar(100) NOT NULL,
  `inputEmail` varchar(100) NOT NULL,
  `contactNumber` varchar(100) NOT NULL,
  `inputPassword` varchar(100) NOT NULL,
  PRIMARY KEY (`userID`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `userregisteration`
--

INSERT INTO `userregisteration` (`userID`, `fullName`, `inputEmail`, `contactNumber`, `inputPassword`) VALUES
(1, 'Ramjee Bharti', 'iiitda@gmail.com', '+910000000000', 'd4395a5856617fa4afe8c5cd2eed3912')
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

index.php

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Google reCaptcha</title>
<!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.1/dist/css/bootstrap.min.css" rel="stylesheet">
	  <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>
<!-- Custom styles for this template -->
<link href="css/style.css" rel="stylesheet">
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>

<body>
<form class="form-signin" id="registration">
  <div class="text-center mb-4"> 
    <h1 class="h3 mb-3 font-weight-normal">User Registration Form With Google reCaptcha</h1>
  </div>
	<div class="form-label-group">
    <input type="text" id="fullName" class="form-control" name="fullName" placeholder="Full Name" autofocus >
    <label for="fullName">Full Name</label>
	<span id="fullName_error" class="text-danger"></span>
  </div>
  <div class="form-label-group">
    <input type="text" id="inputEmail" class="form-control" name="inputEmail" placeholder="Email address" >
    <label for="inputEmail">Email address</label>
	  <span id="inputEmail_error" class="text-danger"></span>
  </div>
	<div class="form-label-group">
    <input type="text" id="contactNumber" class="form-control" name="contactNumber" placeholder="Contact Number" >
    <label for="contactNumber">Contact Number</label>
	<span id="contactNumber_error" class="text-danger"></span>
  </div>
  <div class="form-label-group">
    <input type="password" id="inputPassword" class="form-control" name="inputPassword" placeholder="Password" >
    <label for="inputPassword">Password</label>
	  <span id="inputPassword_error" class="text-danger"></span>
  </div>
   <div class="form-label-group">
     <div class="g-recaptcha" data-sitekey="6LfXXGEbAAAAAHHxPe1nKz8qBAwTCvix5G25yNA7"></div>
	  <span id="captcha_error" class="text-danger"></span>
  </div>
  <button class="btn btn-lg btn-primary btn-block" type="submit" id="signUp" name="signUp">Sign up</button>
</form>
</body>
</html>
<script>
$(document).ready(function(){

 $('#registration').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"processData.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#signUp').attr('disabled','disabled');
   },
   success:function(data)
   {
    $('#signUp').attr('disabled', false);
    if(data.success)
    {
     $('#registration')[0].reset();
     $('#fullName_error').text('');
     $('#inputEmail_error').text('');
     $('#contactNumber_error').text('');
     $('#inputPassword_error').text('');
     $('#captcha_error').text('');
     grecaptcha.reset();
     alert('Data inserted successfully...');
    }
    else
    {
     $('#fullName_error').text(data.fullName_error);
     $('#inputEmail_error').text(data.inputEmail_error);
     $('#contactNumber_error').text(data.contactNumber_error);
     $('#inputPassword_error').text(data.inputPassword_error);
     $('#captcha_error').text(data.captcha_error);
    }
   }
  })
 });

});
</script>	

processData.php

<?php
include "dbConfig.php";
//processData.php

//if(isset($_POST["signUp"]))
//{
if(isset($_POST['fullName'])) {
 $fullName = '';
 $inputEmail = '';
 $contactNumber = '';
 $inputPassword = '';

 $fullName_error = '';
 $inputEmail_error = '';
 $contactNumber_error = '';
 $inputPassword_error = '';
 $captcha_error = '';

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

 if(empty($_POST["inputEmail"]))
 {
  $inputEmail_error = 'Email is required';
 }
 else
 {
  if(!filter_var($_POST["inputEmail"], FILTER_VALIDATE_EMAIL))
  {
   $inputEmail_error = 'Invalid Email';
  }
  else
  {
   $inputEmail = $_POST["inputEmail"];
  }
 }

 if(empty($_POST["contactNumber"]))
 {
  $contactNumber_error = 'Contact Number is required';
 }
 else
 {
  $contactNumber = $_POST["contactNumber"];
 }

if(empty($_POST["inputPassword"]))
 {
  $inputPassword_error = 'Password is required';
 }
 else
 {
  $inputPassword = $_POST["inputPassword"];
 }
	
 if(empty($_POST['g-recaptcha-response']))
 {
  $captcha_error = 'Captcha is required';
 }
 else
 {
  //$secret_key = '6LfXXGEbAAAAAPCHHrAWxG-Zbg2dJiOxMtnei0aX';
  $url = "https://www.google.com/recaptcha/api/siteverify";
  $privateKey = "6LfXXGEbAAAAAPCHHrAWxG-Zbg2dJiOxMtnei0aX";
  $response = file_get_contents($url.'?secret='.$privateKey.'&response='.$_POST['g-recaptcha-response'].'&remoteip='.$_SERVER['REMOTE_ADDR']);

  $response_data = json_decode($response);

  if($response_data->success){
	  //first validate then insert in db
        $fullName = $_POST['fullName'];
        $inputEmail = $_POST['inputEmail'];
        $contactNumber = $_POST['contactNumber'];
	  	$inputPassword = $_POST['inputPassword'];
        mysqli_query($conn, "INSERT INTO userregisteration(fullName, inputEmail ,contactNumber,inputPassword) VALUES('" . $_POST['fullName'] . "', '" . $_POST['inputEmail'] . "','" . $_POST['contactNumber'] . "', '" . md5($_POST['inputPassword']) . "')");
        }
	 else
  {
   $captcha_error = 'Captcha verification failed';
  }
 }

 if($fullName_error == '' && $inputEmail_error == '' && $contactNumber_error == '' && $inputPassword_error == '' && $captcha_error == '')
 {
  $data = array(
   'success'  => true
  );
 }
 else
 {
  $data = array(
   'fullName_error' => $fullName_error,
   'inputEmail_error' => $inputEmail_error,
   'contactNumber_error'  => $contactNumber_error,
   'inputPassword_error' => $inputPassword_error,
   'captcha_error'  => $captcha_error
  );
 }

 echo json_encode($data);
}

?>

dbConfig.php

<?php $servername='localhost';
    $username='root';
    $password='';
    $dbname = "recaptcha";
    $conn=mysqli_connect($servername,$username,$password,"$dbname");
      if(!$conn){
          die('Could not Connect MySql Server:' .mysql_error());
        }
?>