PHP and Google reCAPTCHA Integration on Submitting a Form Tutorial

Introduction

In this tutorial, I will show you a way to Integrate PHP and Google reCAPTCHA for submitting a form. Here I will also teach you how to add reCAPTCHA to your site. The tutorial aims to provide students and new PHP Programmers to have a reference to learn with for securing their web applications. Here, images, snippets, and sample source codes are provided.

What is Google reCAPTCHA?

To prevent malicious malware from abusing your website, reCAPTCHA employs an advanced risk analysis engine and adaptive challenges. False users will be barred while real users can log in, make purchases, access pages, or create accounts.

How to Add reCaptcha to your site?

Go to https://www.google.com/recaptcha/admin/create. Fill in all the required fields to get your site key and secret key.

Google reCaptcha

Then save the given Site Key and Secret Key.

Google reCaptcha

Then, to add the Google reCaptcha. Here are the following scripts you need to add to you site. To display the reCaptcha checkbox.

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

Add the above script to your page header to include the Google Recaptcha API to your site. Then to add the check box, paste the following script to the location you want to display the Google reCaptcha Checkbox.

  1. <div class="g-recaptcha" data-sitekey="your-site-key"></div>

Verification

When submitting the form, make sure to verify the response using the google reCaptcha verification API. To verify the response, you will be needing the given secret key. Here's the following sample to do so.

  1. <?php
  2. $secret = "6Lck3IAiAAAAAJ7l_ghRD3hIjBT4wxEWQKP6LluJ";
  3. $http_query = http_build_query(["response" => $grr, "secret" => $secret]);
  4.  
  5. $ch = curl_init("https://www.google.com/recaptcha/api/siteverify?".$http_query);
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  7. $result = curl_exec($ch);
  8.  
  9. $response = (array) json_decode($result);
  10.  
  11. if(isset($response['success']) && !$response['success']){
  12.     //Successfull Verification
  13. }else{
  14.     //Verification Failed
  15.     // user $response['error-codes'] to list all the error upon verification
  16. }

Example

The below snippet is an example PHP script that demonstrates the PHP and Google reCaptcha API. The source code result is a simple registration form app that registers the members of an organization. The form has a reCaptcha feature included both on the client and server sides.

index.php

  1. <?php
  2. session_start();
  3. include_once('register.php');
  4. ?>
  5. <!DOCTYPE html>
  6. <html lang="en">
  7.     <meta charset="UTF-8">
  8.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  9.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  10.     <title>Form with Google ReCaptcha</title>
  11.    
  12.     <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  13.     <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  14.     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  15.     <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  16.     <style>
  17.         html, body{
  18.             min-height:100%;
  19.             width:100%;
  20.         }
  21.         .img-holder {
  22.             text-align: center;
  23.             height: 20vw;
  24.             border: 1px solid;
  25.             width: 100%;
  26.             display: flex;
  27.             justify-content: center;
  28.             align-items: center;
  29.             background: black;
  30.         }
  31.         .img-holder > img{
  32.             max-height:calc(100%);
  33.             max-width:calc(100%);
  34.             object-fit:scale-down;
  35.             object-position:center center;
  36.         }
  37.     </style>
  38. </head>
  39.     <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  40.         <div class="container">
  41.             <a class="navbar-brand" href="./">Registration Form with ReCaptcha</a>
  42.             <div>
  43.                 <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  44.             </div>
  45.         </div>
  46.     </nav>
  47.     <div class="container-fluid px-5 my-3">
  48.         <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  49.             <div class="card rounded-0 shadow">
  50.                 <div class="card-body">
  51.                     <div class="container-fluid">
  52.                         <?php if(isset($_SESSION['success_msg'])): ?>
  53.                         <div class="alert alert-success rounded-0">
  54.                             <?= $_SESSION['success_msg'] ?>
  55.                         </div>
  56.                         <?php unset($_SESSION); ?>
  57.                         <?php endif; ?>
  58.                         <?php if(isset($error_msg)): ?>
  59.                         <div class="alert alert-danger rounded-0">
  60.                             <?= $error_msg ?>
  61.                         </div>
  62.                         <?php unset($error_msg); ?>
  63.                         <?php endif; ?>
  64.                         <form action="" method="POST">
  65.                             <div class="mb-3">
  66.                                 <label for="first_name" class="form-label">First Name</label>
  67.                                 <input type="text" class="form-control rounded-0" id="first_name" name="first_name" value="<?= (isset($_POST['first_name']) ? $_POST['first_name'] : "") ?>" required>
  68.                             </div>
  69.                             <div class="mb-3">
  70.                                 <label for="middle_name" class="form-label">Middle Name</label>
  71.                                 <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" value="<?= (isset($_POST['middle_name']) ? $_POST['middle_name'] : "") ?>" required>
  72.                             </div>
  73.                             <div class="mb-3">
  74.                                 <label for="last_name" class="form-label">Last Name</label>
  75.                                 <input type="text" class="form-control rounded-0" id="last_name" name="last_name" value="<?= (isset($_POST['last_name']) ? $_POST['last_name'] : "") ?>" required>
  76.                             </div>
  77.                             <div class="mb-3">
  78.                                 <label for="email" class="form-label">Email</label>
  79.                                 <input type="email" class="form-control rounded-0" id="email" name="email" value="<?= (isset($_POST['email']) ? $_POST['email'] : "") ?>" required>
  80.                             </div>
  81.                             <div class="mb-3">
  82.                                 <label for="contact" class="form-label">Contact #</label>
  83.                                 <input type="text" class="form-control rounded-0" id="contact" name="contact" value="<?= (isset($_POST['contact']) ? $_POST['contact'] : "") ?>" required>
  84.                             </div>
  85.                             <div class="mb-3">
  86.                                 <div class="g-recaptcha" data-sitekey="your-site-key"></div>
  87.                             </div>
  88.                             <?php if(isset($err_captcha)): ?>
  89.                             <div class="alert alert-danger rounded-0 mb-3">
  90.                                 <?= $err_captcha ?>
  91.                             </div>
  92.                             <?php unset($err_captcha); ?>
  93.                             <?php endif; ?>
  94.                             <div class="mb-3 d-grid">
  95.                                 <button class="btn btn-primary btn-block rounded-pill">Register</button>
  96.                             </div>
  97.                         </form>
  98.                     </div>
  99.                 </div>
  100.             </div>
  101.         </div>
  102.     </div>
  103. </body>
  104. </html>

register.php

  1. <?php
  2.     require_once("db-connect.php");
  3.     if($_SERVER['REQUEST_METHOD'] == "POST"){
  4.         extract($_POST);
  5.         $grr = $_POST['g-recaptcha-response'];
  6.         if(empty($grr)){
  7.             $err_captcha = "Kindly check reCaptcha Checkbox before submitting the form.";
  8.         }else{
  9.             /**
  10.              * Validate Google reCaptcha
  11.              */
  12.    
  13.             //  Secret key
  14.             $secret = "your-secret-key";
  15.    
  16.             // Get verification response
  17.    
  18.             $http_query = http_build_query(["response" => $grr, "secret" => $secret]);
  19.    
  20.             $ch = curl_init("https://www.google.com/recaptcha/api/siteverify?".$http_query);
  21.             curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  22.             $result = curl_exec($ch);
  23.             curl_close($ch);
  24.    
  25.             $response = (array) json_decode($result);
  26.             if(isset($response['success']) && !empty($response['success'])){
  27.                 $sql = "INSERT INTO `members` (`first_name`, `middle_name`, `last_name`, `email`, `contact`)
  28.                        VALUES ('{$first_name}', '{$middle_name}', '{$last_name}', '{$email}', '{$contact}')";
  29.                 $insert = $conn->query($sql);
  30.                 if($insert){
  31.                     $_SESSION['success_msg'] = "Data has been saved successfully";
  32.                     header('location: ./');
  33.                     exit;
  34.                 }else{
  35.                     $error_msg = "There's an error occurred while saving the data";
  36.                 }
  37.             }else{
  38.                 $err_captcha = "reCaptcha Validation Failed. <br>";
  39.                 if(isset($response['error-codes']) && count($response['error-codes'])){
  40.                     $err_captcha .= "<ul>";
  41.                     foreach($response['error-codes'] as $error){
  42.                         $err_captcha .= "<li>{$error}</li>";  
  43.                     }
  44.                     $err_captcha .= "</ul>";  
  45.                 }
  46.                 $err_captcha = "Please check the checkbox.";
  47.             }
  48.         }
  49.     }

The complete source code of the above example application can be downloaded on this site for free. The download button is located below this article. The source code zip file also contains the sample or the dummy database schema.

DEMO VIDEO

That's the end of this tutorial. I hope this PHP and Google Recaptcha Integration Tutorial will help you with what you are looking for and will be useful for your current and future PHP Projects.

Explore more on this website for more Tutorials and Free Source Codes

Add new comment