Google reCAPTCHA is designed to protect websites from spam and abuse. It helps to integrate CAPTCHA functionality into the web page without any hassle. You can add Google reCAPTCHA in HTML form and verify the submission using PHP. With the reCAPTCHA widget, the user needs to select the checkbox to verify as a human. The reCAPTCHA checkbox is the best replacement for the generic CAPTCHA code verification that provides a user-friendly way for spam protection.
The Google reCAPTCHA can be implemented in the popup box or modal window. You can add reCAPTCHA widget to the HTML form embedded in a dialog box and validate the response with Ajax. In this tutorial, we will show you how to integrate Google reCAPTCHA in modal popup form with Ajax and PHP.
In the example Google reCAPTCHA Ajax Form script, we will add reCAPTCHA checkbox widget to the contact form in the popup box and validate the response with Ajax submission using PHP.
Before getting started, you need to register the domain of your website and generate reCAPTCHA API keys.
Register a new site:
Go to the Google reCAPTCHA Admin console and register domain.
Click SUBMIT to proceed.
Get Site Key and Secret Key:
After the submission, your site will be registered with reCAPTCHA v2 and the API keys will be generated. The Site Key and Secret Key need to be specified in the script at the time of calling Google reCAPTCHA API.
Copy the Site Key and Secret Key for later use in the Google reCAPTCHA v2 API integration code.
At first, we need to create a modal component to build a popup box and embed an HTML form on it. In this example, we will use Bootstrap’s modal component for the popup window.
1. Include jQuery library.
<script src="js/jquery.min.js"></script>
2. Include the CSS and JS library files of Bootstrap.
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/bootstrap.min.js"></script>
3. Create a button element that will trigger the modal popup.
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
Launch Contact Modal
</button>
4. Define HTML elements to build a modal window.
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Contact Us</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form id="contactForm">
<div class="modal-body">
<div class="frm-status"></div>
<div class="mb-3">
<label class="form-label">Name</label>
<input type="text" class="form-control" name="name" placeholder="Enter your name" required>
</div>
<div class="mb-3">
<label class="form-label">Email</label>
<input type="email" class="form-control" name="email" placeholder="Enter email address" required>
</div>
<div class="mb-3">
<label class="form-label">Message</label>
<textarea class="form-control" name="message" rows="3" placeholder="Your message here..." required></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
In the previous step, we created a modal popup component and added the form elements in the popup. Now, we will add the reCAPTCHA widget in the popup form.
1. Load the reCAPTCHA JavaScript API library before the HTML form popup element.
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
2. Add g-recaptcha
tag under the popup form where you want to display the reCAPTCHA checkbox widget.
g-recaptcha
.data-sitekey
attribute.<div class="mb-3">
<!-- reCAPTCHA widget -->
<div class="g-recaptcha" data-sitekey="Your_reCAPTCHA_Site_Key"></div>
</div>
We will use the Ajax method to submit the form data and reCAPTCHA response to the server-side script (form_submit.php
).
<script>
// Form submit handler
document.querySelector("#contactForm").addEventListener("submit", function(e){
e.preventDefault();
// Post form data via ajax request
$.ajax({
type:'POST',
url:'form_submit.php',
dataType: "json",
data: $('#contactForm').serialize()+'&submit=1',
beforeSend: function () {
$(":input").prop("disabled", true);
$(':button[type="submit"]').prop("disabled", true);
$(':button[type="submit"]').text('Submitting...');
},
success:function(data){
if(data.status == 1){
$('#contactForm')[0].reset();
$('.frm-status').html('<div class="alert alert-success">'+data.msg+'</div>');
}else{
$('.frm-status').html('<div class="alert alert-danger">'+data.msg+'</div>');
}
$(':button[type="submit"]').prop("disabled", false);
$(':button[type="submit"]').text('Submit');
$(":input").prop("disabled", false);
// Reinitialize recaptcha widget
grecaptcha.reset();
}
});
});
</script>
In this server-side script (form_submit.php
), we will verify the user’s response and process the contact request.
g-recaptcha-response
POST parameter to get the user’s response token from the client-side reCAPTCHA widget.secret
), response token (response
), and user’s IP (remoteip
) in POST parameters.<?php
// Google reCAPTCHA API keys settings
$secretKey = 'Your_reCaptcha_Secret_Key';
// Email settings
$recipientEmail = 'admin@example.com';
// If form data is submitted by AJAX request
if(isset($_POST['submit'])){
// Define default response
$response = array(
'status' => 0,
'msg' => 'Something went wrong, please try again after some time.'
);
// Retrieve value from the form input fields
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
$valErr = '';
if(empty($name)){
$valErr .= 'Please enter your name.<br/>';
}
if(empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$valErr .= 'Please enter a valid email.<br/>';
}
if(empty($message)){
$valErr .= 'Please enter your message.<br/>';
}
if(empty($valErr)){
// Validate reCAPTCHA response
if(!empty($_POST['g-recaptcha-response'])){
// Google reCAPTCHA verification API Request
$api_url = 'https://www.google.com/recaptcha/api/siteverify';
$resq_data = array(
'secret' => $secretKey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
);
// Initialize cURL request
$curlConfig = array(
CURLOPT_URL => $api_url,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $resq_data,
CURLOPT_SSL_VERIFYPEER => false
);
$ch = curl_init();
curl_setopt_array($ch, $curlConfig);
$response = curl_exec($ch);
if (curl_errno($ch)) {
$api_error = curl_error($ch);
}
curl_close($ch);
// Decode JSON data of API response in array
$responseData = json_decode($response);
// If the reCAPTCHA API response is valid
if(!empty($responseData) && $responseData->success){
// Send email notification to the site admin
$to = $recipientEmail;
$subject = 'New Contact Request Submitted';
$htmlContent = "
<h4>Contact request details</h4>
<p><b>Name: </b>".$name."</p>
<p><b>Email: </b>".$email."</p>
<p><b>Message: </b>".$message."</p>
";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
// Sender info header
$headers .= 'From:'.$name.' <'.$email.'>' . "\r\n";
// Send email
@mail($to, $subject, $htmlContent, $headers);
$response = array(
'status' => 1,
'msg' => 'Thank you! Your contact request has been submitted successfully.'
);
}else{
$response['msg'] = !empty($api_error)?$api_error:'The reCAPTCHA verification failed, please try again.';
}
}else{
$response['msg'] = 'Please check the reCAPTCHA checkbox.';
}
}else{
$valErr = !empty($valErr)?'<br/>'.trim($valErr, '<br/>'):'';
$response['msg'] = 'Please fill all the mandatory fields:'.$valErr;
}
// Return response
echo json_encode($response);
}
?>
Integrate Google reCAPTCHA v3 in HTML Form with PHP
The popup element is very useful to display multiple sections in a single web page. Using Bootstrap’s JavaScript modal plugin, you can add a dialog window to the web page with HTML and CSS. This example code helps you to protect the form on the popup using the reCAPTCHA checkbox in HTML. Here we have used contact form elements, but you can add any type of form (login, registration, etc.) to popup and integrate Google reCAPTCHA protection to Ajax form in popup box.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request