Google reCAPTCHA is a CAPTCHA system that helps web hosts differentiate between human and bot access to web pages. In the previous version of Google reCAPTCHA, the user is required to select a checkbox in the CAPTCHA widget. This checkbox feature is removed in the latest version of reCAPTCHA. The reCAPTCHA v3 enhances the user experience where spam protection can be extended across the website rather than limited to the specific web form or pages.
Google reCAPTCHA v3 enables the protection of web forms or web pages from getting spam. You can verify to check if an interaction is legitimate without any user interaction using reCAPTCHA v3. The user doesn’t require to do any activity to confirm that they are not a robot. The reCAPTCHA API will detect fraud access and stop bots to prevent automated attacks on the website. In this tutorial, we will show you how to integrate Google reCAPTCHA v3 in HTML form with PHP.
In the example code, the following functionality will be implemented to demonstrate the Google reCAPTCHA v3 integration with PHP.
The reCAPTCHA keys are required to call the Google reCAPTCHA API. Before adding the reCAPTCHA v3 widget to a webpage, you need to register your website and get reCAPTCHA API keys.
Register a new site:
Register the reCAPTCHA v3 keys on the Google reCAPTCHA Admin console.
Click SUBMIT to proceed.
Get Site Key and Secret Key:
After the submission, your site will be registered with reCAPTCHA v3 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 v3 API integration code.
The reCAPTCHA v3 does not interrupt the user and the widget is added to the bottom-right corner of the web page. So, you can bind reCAPTCHA v3 to any action and run it whenever you want.
First, load the reCAPTCHA API JavaScript library.
<script src="https://www.google.com/recaptcha/api.js"></script>
Define a callback function to handle the reCAPTCHA token submission using JavaScript.
<script>
function onSubmit(token) {
document.getElementById("contactForm").submit();
}
</script>
Add predefined attributes to the HTML button, so that reCAPTCHA API will bind the challenge automatically to this button.
data-sitekey
attribute.data-callback
attribute.<button class="g-recaptcha"
data-sitekey="reCAPTCHA_Site_Key"
data-callback='onSubmit'
data-action='submit'>Submit</button>
Here is the HTML code example to integrate reCAPTCHA v3 to form.
<form id="contactForm" method="post" action="">
<!-- Form fields -->
<div class="input-group">
<input type="text" name="name" value="" placeholder="Your name">
</div>
<div class="input-group">
<input type="email" name="email" value="" placeholder="Your email">
</div>
<div class="input-group">
<textarea name="message" placeholder="Type message..."></textarea>
</div>
<input type="hidden" name="submit_frm" value="1">
<!-- Submit button with reCAPTCHA trigger -->
<button class="g-recaptcha"
data-sitekey="Your_reCAPTCHA_Site_Key"
data-callback='onSubmit'
data-action='submit'>Submit</button>
</form>
After the form submission, the reCAPTCHA challenge will be submitted to the application’s backend to 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 script.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';
// Assign default values
$postData = $valErr = $statusMsg = $api_error = '';
$status = 'error';
// If the form is submitted
if(isset($_POST['submit_frm'])){
// Retrieve value from the form input fields
$postData = $_POST;
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$message = trim($_POST['message']);
// Validate input fields
if(empty($name)){
$valErr .= 'Please enter your name.<br/>';
}
if(empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$valErr .= 'Please enter a valid email.<br/>';
}
if(empty($message)){
$valErr .= 'Please enter message.<br/>';
}
// Check whether submitted input data is valid
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']
);
$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);
$status = 'success';
$statusMsg = 'Thank you! Your contact request has been submitted successfully.';
$postData = '';
}else{
$statusMsg = !empty($api_error)?$api_error:'The reCAPTCHA verification failed, please try again.';
}
}else{
$statusMsg = 'Something went wrong, please try again.';
}
}else{
$valErr = !empty($valErr)?'<br/>'.trim($valErr, '<br/>'):'';
$statusMsg = 'Please fill all the mandatory fields:'.$valErr;
}
}
?>
Use the following code in the HTML form to display the form submission status message at the client-side script.
<?php if(!empty($statusMsg)){ ?>
<p class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>
Custom Captcha Library with PHP
There are various libraries and plugins are available to add CAPTCHA functionality to the web pages. The Google reCAPTCHA v3 is the powerful and easiest option to add CAPTCHA protection to the web form without any interaction from the user. The user does not require to solve any CAPTCHA challenge to process action. The reCAPTCHA v3 handles spam and malicious request to protect websites by blocking fake users. Not only the web form but also you can use the reCAPTCHA v3 in the web pages throughout the web application.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
How to implement in wordpress?
Hi. I have implemented the script and uploaded the files on server.
it says displays success message also, but I have not received any message in my inbox.
HI, Thanks for this. I am new to this so it was really helpful. I just have one question. With reCAPTCHA v3 shouldn’t you also check that $responseData->score if below your chosen threshold e.g 0.5 before sending the email?