Skip to main content

How do I add google reCAPTCHA to my website?

google reCAPTCHA tutorial for beginners

Introduction

In this blog, we will learn how to add google reCAPTCHA to website. Adding google reCAPTCHA protects your website form spam comments, messages, and any kind of attacks that spammers and attackers do. In this blog we will implement google reCAPTCHA in our website's contact form. You can add this reCAPTCHA in your comment form too. We will cover both client side and server side integration that help you to implement reCAPTCHA in your own website.

Step 1: Register your website on google reCAPTCHA.

1. Enter you website name on the label.
2. Select the reCAPTCHA type (v2 or v3).
3. Add domain URL. You can add multiple domains inside this.
4. After filling all the fields, click on the submit button.


Step 2: Get your site key and secret key

Once registered, Now you get the site key and secret key. site key which we will use in client side (in html code) and secret key which we will use in server side (in PHP code for communication between website and reCAPTCHA ). keep your secret key private.



Step 3: Visit the google reCAPTCHA developer guide

Google reCAPTCHA developer's guide for complete documentation on both client side and server side integration.

Step 4: Client side integration

1. Copy script tag from the html snippet and paste it inside the head tag on your contact form or you can copy it directly from here without visit the developer's guide.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>

2. Similarly copy the div element and paste it before the submit button on your contact form or you can copy it directly from here.
<div class="g-recaptcha" data-sitekey="your_site_key"></div>

3. Replace your_site_key with your actual site key.



4. After doing all the above steps of client side integration you are successfully added reCAPTCHA on your contact form that looks like this.


Integrate google recaptcha in php form

Step 5: Server side integration

1. When the form is submitted. Google sends the reCAPTCHA response as a POST parameter named g-recaptcha-response. You need to validate this on your server.

2. Access the response token using $_POST and check the response token exists using isset() before sending it to google for verification.
  if (isset($_POST['g-recaptcha-response'])) {
      $responseKey = $_POST['g-recaptcha-response'];
  }

3. Define your secret key and use file_get_contents() to verify the response with google. If the verification is successful, continue processing the form.

  if (isset($_POST['g-recaptcha-response'])) {
    $secretKey = "your_secret_key";
    $responseKey = $_POST['g-recaptcha-response'];

    // reCAPTCHA API request without remoteip
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";

    $response = file_get_contents($url);
    $response = json_decode($response);

    if ($response->success) {
        echo "Form submitted successfully!";
        // You can handle your form data here
    } else {
        echo "reCAPTCHA verification failed!";
    }
  } else {
      echo "Please complete the reCAPTCHA.";
  }

Note: In the post request to google's reCAPTCHA api, the remoteip parameter (which holds user's IP address) is optional. You can safely skip it without affecting verification. In this blog, we will omit the remoteip parameter for simplicity.




Now every thing is done, we follow all the above steps and successfully added the google reCAPTCHA on the contact page with client side and server side integration.

Here is code snippet with explanation for your better understanding how the actual code works.

File name: contact.php

     
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <title>Contact</title>
          <link
            href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
            rel="stylesheet"
            integrity="sha384-4Q6Gf2aSP4eDXB8Miphtr37CMZZQ5oXLH2yaXMJ2w8e2ZtHTl7GptT4jmndRuHDT"
            crossorigin="anonymous"
          />
          <script src="https://www.google.com/recaptcha/api.js" async defer></script>
      </head>
      <body>
          <div class="container col-6">
            <h1 class="text-center"><b>Contact</b></h1>
            <form action="contact-process.php" method="post"
                class="d-flex flex-column gap-4 mb-4 py-4" novalidate>
              <div>
                <label class="form-label" for="name">Name</label>
              <input class="form-control" name="name" type="text" autocomplete="off"
                placeholder="Name*" id="name" required>
              </div>
              <div>
                <label class="form-label" for="email">Email</label>
              <input class="form-control" name="email" type="email" autocomplete="off"
                placeholder="Email*" id="email" required>
              </div>
              <div>
                <label class="form-label" for="message">Message</label>
              <textarea class="form-control" name="message" autocomplete="off"
                placeholder="Message*" rows="3" id="message" required></textarea>
              </div>
              <div class="g-recaptcha" data-sitekey="your_site_key"></div>
              <button class="btn btn-primary" type="submit">Send</button>
            </form>
          </div>
      </body>
      </html>


Explanation:
  1. We added a Bootstrap CDN link in the <head> section to style the form using Bootstrap classes. This helps avoid writing custom CSS and gives a clean, responsive design.
  2. We included the <script> tag (for loading the reCAPTCHA API) and the <div class="g-recaptcha"> element (to show the checkbox). These are added as described in Step 4: Client side integration. Don't forget to replace "your_site_key" with your actual site key from google.
  3. We created a simple contact form where each field includes a <label>.
  4. The form's action is set to contact-process.php, which means the submitted data will be sent to that PHP file for server side processing.

File name: contact-process.php

PHP script with google reCAPTCHA validation
       
        <?php
        include "connect.php";

        $name = mysqli_real_escape_string($conn, $_POST['name']);
        $email = mysqli_real_escape_string($conn, $_POST['email']);
        $message = mysqli_real_escape_string($conn, $_POST['message']);

        if (!empty($name) && !empty($email) && !empty($message)) {

            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

                if (isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])) {

                    $secretKey = "your_secret_key";
                    $responseKey = $_POST['g-recaptcha-response'];

                    $verifyResponse = file_get_contents("https://www.google.com/recaptcha/api/siteverify?
                    secret=".$secretKey."&response=".$responseKey);

                    $response = json_decode($verifyResponse);

                    if ($response->success) {

                        $query = "INSERT INTO contacts (name, email, message) VALUES (?, ?, ?)";

                        $stmt = mysqli_prepare($conn, $query);
                        mysqli_stmt_bind_param($stmt, "sss", $name, $email, $message);

                        if (mysqli_stmt_execute($stmt)) {
                            echo "message sent successfully!";
                        } else {
                            echo "Failed to send message.";
                        }
                    } else {
                        echo "Error in recaptcha verifaction.";
                    }
                } else {
                    echo "Oops! You need to verify that you're not a robot.";
                }
            } else {
                echo "Enter a valid email.";
            }
        } else {
            echo "All fields are required.";
        }


Explanation:
  1. Include the database connection file (connect.php) that connect with the database.
  2. Retrieves form values using $_POST, Uses mysqli_real_escape_string() to escape special characters, that helps to prevent SQL injection.
  3. Ensures that all fields are filled. If any field is empty an error message shows to the user.
  4. Check if the email is in a valid format.
  5. Ensures the g-recaptcha-response exists in the POST data and not empty.
  6. Sends a GET request to google's API to verify the token and parses the JSON response returned by google into a PHP object ($response).
  7. If success response is true, the reCAPTCHA is valid and the form submission is verified as human.
  8. Uses a prepared statement to safely insert the sanitized data into the contacts table, sss means all three values are strings.
  9. If the insert query is successfully executed it shows a success message, otherwise an error message occurred.

File name: query.sql

   
    CREATE DATABASE `blogger`;

    USE blogger;

    CREATE TABLE `contacts` (
        contact_id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) NOT NULL,
        email VARCHAR(255) NOT NULL,
        message TEXT NOT NULL,
        sent_at DATETIME DEFAULT CURRENT_TIMESTAMP
    );


Explanation:
  1. Create a database named 'blogger';
  2. Switch to the blogger database and create a table called contacts that contains contact_id, name, email, message, and sent_at column.
  3. The sent_at column automatically stores the date and time when the message is submitted. It is useful for tracking user activity or organizing messages by time.

Conclusion

In this blog, we explored how to add google reCAPTCHA to website's contact form. Now your website is ready to handle spam and bot submissions, and ensure that the form is submitted by the user. There are many tools and website by which you can add captcha in your website such as hcaptcha, cloudflare turnstile, and wpforms. We will cover all of these in future.

Comments

Popular posts from this blog

Leetcode SQL 50 interview questions with solution: A Guide for Coders

Introduction Hi coders, In this blog, we will tackle SQL questions from LeetCode. If you're a coder, a computer science student, or simply interested in coding, you may be familiar with LeetCode. It's a platform where coding enthusiasts practice problems to enhance their critical thinking and problem-solving skills. Most of us practice programming questions on leetcode so here we practice SQL questions which is taken from leetcode. We'll start with basic SQL questions focused on SELECT , joins, and aggregate functions. Once we've covered these foundational topics, we'll transition to more advanced concepts. Before diving into the questions, ensure you have a basic understanding of SQL syntax and statements, including SELECT , various joins (self join, left join, right join, outer join), and basic aggregate functions. Here are some SQL interview questions with solution: Q1 1757. Recyclable and Low Fat Products SELECT product_id FROM Products WHERE low_fats ...

How to Create a Responsive Website Using CSS - A Step-by-Step Guide.

Introduction Creating a responsive website is not an option, It's number one priority for a developer to make a website responsive. A responsive website adjusts according to different screen sizes, providing an optimal user experience on desktops, tablets, and mobile devices. For creating a responsive website, You don't need JavaScript to make your website responsive, HTML and CSS are enough. In this guide, we will walk through the key techniques to build a fully responsive web page from scratch. Why is Responsiveness Important? A responsive website offers several benefits, including: Better User Experience - Ensures your content is readable on all devices. Improved SEO Ranking - Mobile-friendly websites rank higher in search results. Faster Loading Times - Optimized layouts prevent unnecessary resource consumption. Increased Engagement - Users stay longer on a site that adapts well to their screen. Now, let's dive into the essential techniques to create a responsive we...

What is Git and GitHub. Difference Between Git and GitHub. Workflow of Git.

Introduction In this blog, we will dive into a Git and GitHub, understand their differences, and go over the typical workflow when using GitHub. Whether you are new to version control or simply curious about how these tools work together, this guide will walk you through the essential concepts and processes you need to know. What is Git? Git is a Distributed Version Control System (DVCS) that efficiently manages code changes across multiple contributors. It helps developers to monitor and manage changes in their code efficiently. Git was created by Linus Torvalds on April 7, 2005. It is widely used in developer community for its collaborative features, allowing developers to work on the same project, whether the project is small or large. You can efficiently monitor code modifications and preserve a detailed history of changes. Git is free and open-source, designed to handle everything from individual projects to complex ones. Developers can track every modification, create branches fo...