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. html, body{
  17. min-height:100%;
  18. width:100%;
  19. }
  20. .img-holder {
  21. text-align: center;
  22. height: 20vw;
  23. border: 1px solid;
  24. width: 100%;
  25. display: flex;
  26. justify-content: center;
  27. align-items: center;
  28. background: black;
  29. }
  30. .img-holder > img{
  31. max-height:calc(100%);
  32. max-width:calc(100%);
  33. object-fit:scale-down;
  34. object-position:center center;
  35. }
  36. </style>
  37. </head>
  38. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  39. <div class="container">
  40. <a class="navbar-brand" href="./">Registration Form with ReCaptcha</a>
  41. <div>
  42. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  43. </div>
  44. </div>
  45. </nav>
  46. <div class="container-fluid px-5 my-3">
  47. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
  48. <div class="card rounded-0 shadow">
  49. <div class="card-body">
  50. <div class="container-fluid">
  51. <?php if(isset($_SESSION['success_msg'])): ?>
  52. <div class="alert alert-success rounded-0">
  53. <?= $_SESSION['success_msg'] ?>
  54. </div>
  55. <?php unset($_SESSION); ?>
  56. <?php endif; ?>
  57. <?php if(isset($error_msg)): ?>
  58. <div class="alert alert-danger rounded-0">
  59. <?= $error_msg ?>
  60. </div>
  61. <?php unset($error_msg); ?>
  62. <?php endif; ?>
  63. <form action="" method="POST">
  64. <div class="mb-3">
  65. <label for="first_name" class="form-label">First Name</label>
  66. <input type="text" class="form-control rounded-0" id="first_name" name="first_name" value="<?= (isset($_POST['first_name']) ? $_POST['first_name'] : "") ?>" required>
  67. </div>
  68. <div class="mb-3">
  69. <label for="middle_name" class="form-label">Middle Name</label>
  70. <input type="text" class="form-control rounded-0" id="middle_name" name="middle_name" value="<?= (isset($_POST['middle_name']) ? $_POST['middle_name'] : "") ?>" required>
  71. </div>
  72. <div class="mb-3">
  73. <label for="last_name" class="form-label">Last Name</label>
  74. <input type="text" class="form-control rounded-0" id="last_name" name="last_name" value="<?= (isset($_POST['last_name']) ? $_POST['last_name'] : "") ?>" required>
  75. </div>
  76. <div class="mb-3">
  77. <label for="email" class="form-label">Email</label>
  78. <input type="email" class="form-control rounded-0" id="email" name="email" value="<?= (isset($_POST['email']) ? $_POST['email'] : "") ?>" required>
  79. </div>
  80. <div class="mb-3">
  81. <label for="contact" class="form-label">Contact #</label>
  82. <input type="text" class="form-control rounded-0" id="contact" name="contact" value="<?= (isset($_POST['contact']) ? $_POST['contact'] : "") ?>" required>
  83. </div>
  84. <div class="mb-3">
  85. <div class="g-recaptcha" data-sitekey="your-site-key"></div>
  86. </div>
  87. <?php if(isset($err_captcha)): ?>
  88. <div class="alert alert-danger rounded-0 mb-3">
  89. <?= $err_captcha ?>
  90. </div>
  91. <?php unset($err_captcha); ?>
  92. <?php endif; ?>
  93. <div class="mb-3 d-grid">
  94. <button class="btn btn-primary btn-block rounded-pill">Register</button>
  95. </div>
  96. </form>
  97. </div>
  98. </div>
  99. </div>
  100. </div>
  101. </div>
  102. </body>
  103. </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. }else{
  34. $error_msg = "There's an error occurred while saving the data";
  35. }
  36. }else{
  37. $err_captcha = "reCaptcha Validation Failed. <br>";
  38. if(isset($response['error-codes']) && count($response['error-codes'])){
  39. $err_captcha .= "<ul>";
  40. foreach($response['error-codes'] as $error){
  41. $err_captcha .= "<li>{$error}</li>";
  42. }
  43. $err_captcha .= "</ul>";
  44. }
  45. $err_captcha = "Please check the checkbox.";
  46. }
  47. }
  48. }

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