In today’s digital landscape, online security is of utmost importance. One effective way to protect websites from spam and malicious activities is by implementing Google reCAPTCHA. It will improve protection from automated form-filling bots or script attachments for sending dummy data.
In this tutorial, we will take a practical example of integrating Google reCAPTCHA in PHP, step by step. By the end of this guide, you will have a solid understanding of how to add an extra layer of security to your PHP-based website or application.
What is Google reCAPTCHA?
Google reCAPTCHA is a free service provided by Google that helps protect websites from spam and abusive activities, such as automated bot submissions and malicious attacks. It uses advanced algorithms to differentiate between human users and bots, ensuring a better user experience and increased security.
Get Your reCAPTCHA API Keys
To begin, you need to obtain your reCAPTCHA API keys from the official Google reCAPTCHA website. Follow these simple steps:
- Visit the reCAPTCHA website.
- Click on the “Admin Console” button located at the top right corner of the page.
- Sign in to your Google account.
- Register a new site by providing a label and the domain where reCAPTCHA will be used.
- Choose the reCAPTCHA type (v2 Checkbox or v3) based on your requirements.
- Enter your website’s domain in the appropriate fields.
- Accept the terms of service and click on the “Submit” button.
- After successful registration, you will receive your Site Key and Secret Key.
Implementing reCAPTCHA in PHP
After creating reCAPTCHA API keys. let’s create a new PHP file for your project or you can use an existing one.
In that file, we will add the site key and secret. Here, we will take the registration process example to integrate reCAPTCHA protection. Add or modify the below code into a php file:
<?php
$siteKey = "YOUR_SITE_KEY";
$secretKey = "YOUR_SECRET_KEY";
?>
<!DOCTYPE html>
<html>
<head>
<title>Integrating Google reCAPTCHA in PHP</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<h1>User registration</h1>
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br><br>
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div><br><br>
<button type="submit">Register</button>
</form>
</body>
</html>
Here, we have created a simple registration form with name, email, and password as fields. Replace YOUR_SITE_KEY and YOUR_SECRET_KEY with the respective keys you obtained from the reCAPTCHA website.
Save the above file and run this page in a browser and check whether reCAPTCHA is visible or not.
Verifying reCAPTCHA Response
After implementation, let’s validate the reCAPTCHA response and ensure its authenticity.
For that, we will create a new file called “process_form.php” (or use an existing one) to handle the form submission. In this file, we will use Google reCAPTCHA API for validating the reCAPTCHA response. Add the following code:
<?php
$recaptchaResponse = $_POST['g-recaptcha-response'];
$ip = $_SERVER['REMOTE_ADDR'];
$url = 'https://www.google.com/recaptcha/api/siteverify';
$data = array(
'secret' => $secretKey,
'response' => $recaptchaResponse,
'remoteip' => $ip
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === false) {
// Error handling
} else {
$resultData = json_decode($result);
if ($resultData->success) {
// User registration process
} else {
// Display an error message or take appropriate action
}
}
?>
Here, we have validated the reCAPTCHA response with Google using API. Based on the response, we have handled errors in case there are errors like invalid keys or network timeout, or anything else.
If we got a response from Google then based on the response we will process further user registration or display the message.
Conclusion
This tutorial has provided you with a step-by-step guide to implement reCAPTCHA seamlessly into your PHP code. By integrating Google reCAPTCHA into your PHP-based website or application, you can significantly enhance its security and protect it from spam and malicious activities.