Integrate Google reCAPTCHA v3 in HTML Form with PHP - CodexWorld

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.

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.

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=""></script>

Define a callback function to handle the reCAPTCHA token submission using JavaScript.

function onSubmit(token) {

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" 

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 class="input-group">	
        <input type="email" name="email" value="" placeholder="Your email">
    <div class="input-group">
        <textarea name="message" placeholder="Type message..."></textarea>

    <input type="hidden" name="submit_frm" value="1">
    <!-- Submit button with reCAPTCHA trigger -->
    <button class="g-recaptcha" 

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.
// Google reCAPTCHA API keys settings 
$secretKey     'Your_reCaptcha_Secret_Key'
// Email settings 
$recipientEmail ''
// Assign default values
$postData $valErr $statusMsg '';
$status 'error';

// If the form is submitted
// Retrieve value from the form input fields
$postData $_POST
$name trim($_POST['name']); 
$email trim($_POST['email']); 
$message trim($_POST['message']); 
// Validate input fields 
$valErr .= 'Please enter your name.<br/>'
$email) || filter_var($emailFILTER_VALIDATE_EMAIL) === false){ 
$valErr .= 'Please enter a valid email.<br/>'
$valErr .= 'Please enter message.<br/>'
// Check whether submitted input data is valid 
// Validate reCAPTCHA response 
if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
// Google reCAPTCHA verification API Request 
$api_url ''
$resq_data = array( 
'secret' => $secretKey
'response' => $_POST['g-recaptcha-response'], 
'remoteip' => $_SERVER['REMOTE_ADDR'
$curlConfig = array( 
CURLOPT_URL => $api_url
$ch curl_init(); 
$response curl_exec($ch); 
// Decode JSON data of API response in array 
$responseData json_decode($response); 
// If the reCAPTCHA API response is valid 
// Send email notification to the site admin 
$to $recipientEmail
$subject 'New Contact Request Submitted'
                    <h4>Contact request details</h4> 
                    <p><b>Name: </b>"
                    <p><b>Email: </b>"
                    <p><b>Message: </b>"

// 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 
$status 'success'
$statusMsg 'Thank you! Your contact request has been submitted successfully.'
$postData ''
$statusMsg 'The reCAPTCHA verification failed, please try again.'
$statusMsg 'Something went wrong, please try again.'
$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.

Are you want to get implementation help, or modify or enhance the functionality of this script? Submit Paid Service Request

If you have any questions about this script, submit it to our QA community - Ask Question

Leave a reply


Learn more about flight training Programs, costs, timelines, application process and more…