
Nowadays we use captcha to protect our website from spam and malicious bots. These spam bots generate fake data through the website's forms. If the website saves all the form data in the database, then a huge amount of fake data will be saved in the user's database or a huge amount of emails will be sent. And these bots sometimes also launch brute force attacks. To avoid all these issues we use Google reCaptcha. In this article, we will learn about Google Recaptcha V3 PHP implementation in detail with help of examples.
What is Google reCAPTCHA v3?
Google reCaptcha V3 is an easy way to secure website forms without interrupting the user's experience. It runs silently in the background, and when a user or bot fills out a website form, we use Google’s verification API to check captcha response. Based on response, we decide whether the submission is valid or invalid. If its true means valid submission, if its false means invalid submission; this depends on the behavior of the user.
Let's start step by step Google reCaptcha integration for any forms.
Step 1: First of all we have to create an account on Google Recaptcha. Go to Google Recaptcha Admin Console.
Now we have to register our website.
Fields need to fill,
- Label: Here we have to give a name so that we can identify our website in future.
- reCaptcha Type: Here we will select Score Based(v3)
- Domains: Here we will add the domain name of our website. We will not add anything like "http://", "https://" or "www" in the domain name. For example, example.com
After this we will click on the submit button.
When registration is successfully completed, we will get Site Key & Secret Key. Site key is used in frontend website and Secret key is used in backend code. These credentials will be used for both domain & sub-domain of our website. Suppose, "example.com" is our domain and "apps.example.com" is our sub-domain, and we have added "example.com" in the above domain step. So these same credentials will be used for both "example.com" & "apps.example.com".
Step 2: Now we will create an HTML form
index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Google reCaptcha V3 Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.5/dist/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div class="container my-5"> <div class="row justify-content-center"> <div class="col-lg-9"> <h1 class="mb-3">Contact Us</h1> <form action="submit.php" method="post" name="frmcontact" id="frmcontact"> <div class="row g-3"> <div class="col-md-6"> <label for="your-name" class="form-label">Your Name</label> <input type="text" class="form-control" id="name" name="name" required> </div> <div class="col-md-6"> <label for="your-email" class="form-label">Your Email</label> <input type="email" class="form-control" id="email" name="email" required> </div> <div class="col-md-6"> <label for="your-subject" class="form-label">Your Subject</label> <input type="text" class="form-control" id="subject" name="subject"> </div> <div class="col-12"> <label for="your-message" class="form-label">Your Message</label> <textarea class="form-control" id="message" name="message" rows="5" required></textarea> </div> <div class="col-12"> <div class="row"> <div class="col-md-6"> <button class="btn btn-dark w-100 fw-bold g-recaptcha" data-sitekey="site_key" data-callback='validateformsubmit' data-action='submit'>Send</button> </div> </div> </div> </div> </form> </div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script src="https://www.google.com/recaptcha/api.js"></script> <script> function validateformsubmit() { let name = document.getElementById("name").value; let email = document.getElementById("email").value; let subject = document.getElementById("subject").value; let message = document.getElementById("message").value; if(name == "") { alert('Please enter your name'); return false; } else if(email == "") { alert('Please enter your valid email'); return false; } else if(subject == "") { alert('Please enter subject'); return false; } else if(message == "") { alert('Please enter your message'); return false; } else { document.getElementById("frmcontact").submit(); } } </script> </body> </html>
Here we will replace "site_key" with Recaptcha's Site Key.
Step 3: Now we will verify the token in the backend PHP code.
submit.php
<?php $secret_key = "secret_key"; $captcha_resp = $_POST['g-recaptcha-response']; if($captcha_resp && !empty($captcha_resp)) { $response = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.urlencode($secret_key).'&response='.urlencode($captcha_resp)); $responseData = json_decode($response); if(!empty($responseData) && $responseData->success) { echo "Valid User"; } else { echo "Invalid User"; } } else { echo "Captcha Code error"; } ?>
Here we will replace "secret_key" with the Secret Key of reCaptcha.
We should not trust the user during form submission, so input validation is mandatory for all forms.
Conclusion
With Google reCAPTCHA v3, you can safeguard your PHP-based website against spam and misuse in a stylish and unobtrusive manner. You may take more intelligent decisions without sacrificing the user experience by evaluating user behavior and allocating scores.