![]() |
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.
First, go to this link https://www.google.com/recaptcha/admin/create.
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:
- 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.
- 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.
- We created a simple contact form where each field includes a <label>.
- 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:
- Include the database connection file (connect.php) that connect with the database.
- Retrieves form values using $_POST, Uses mysqli_real_escape_string() to escape special characters, that helps to prevent SQL injection.
- Ensures that all fields are filled. If any field is empty an error message shows to the user.
- Check if the email is in a valid format.
- Ensures the g-recaptcha-response exists in the POST data and not empty.
- 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).
- If success response is true, the reCAPTCHA is valid and the form submission is verified as human.
- Uses a prepared statement to safely insert the sanitized data into the contacts table, sss means all three values are strings.
- 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:
- Create a database named 'blogger';
- Switch to the blogger database and create a table called contacts that contains contact_id, name, email, message, and sent_at column.
- 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
Post a Comment