Integrate Google reCAPTCHA v3 in HTML Form with PHP

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.

  • Create an HTML form to submit contact request.
  • Integrate reCAPTCHA v3 API and attach it to the HTML form.
  • Validate request by verifying the user’s response with Google reCAPTCHA API.
  • Retrieve form data and send contact request via email using PHP.

Generate reCAPTCHA v3 API Keys

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.

  • Label – Make it easier for you to identify the site in the future.
  • reCAPTCHA type – Select reCAPTCHA v3 (Verify requests with a score).
  • Domains – Specify the domain of the website.
google-recaptcha-v3-register-website-domain-codexworld

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.

  • Site Key – This key is used in the HTML code of the client-side script.
  • Secret Key – This key helps to authorize communication between your site and the reCAPTCHA server and is used in the server-side script for the user’s response verification.
google-recaptcha-v3-api-keys-create-site-secret-key-codexworld

Copy the Site Key and Secret Key for later use in the Google reCAPTCHA v3 API integration code.

Add reCAPTCHA v3 in the HTML Form

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.

  • Specify the Site Key of the reCAPTCHA v3 in the data-sitekey attribute.
  • Specify the JavaScript callback function in the 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.

  • The reCAPTCHA challenge will bind to the submit button.
  • The response token will submit to the server-side script for verification.
<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>

Verify reCAPTCHA Response with PHP

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.

  • Validate form input fields to check whether the user fills in the correct values.
  • Use g-recaptcha-response POST parameter to get the user’s response token from the client-side script.
  • Execute a cURL request to verify the response token with reCAPTCHA API using PHP.
  • Pass the Site Secret Key (secret), response token (response), and user’s IP (remoteip) in POST parameters.
  • If the reCAPTCHA response is valid and successful, process the contact form submission request further. Otherwise, display an error notification to the user.
<?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($emailFILTER_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

Conclusion

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

2 Comments

  1. Anuradha Said...
  2. Jan Said...

Leave a reply

keyboard_double_arrow_up