How to Integrate Google reCAPTCHA v3 in HTML Form using PHP


0

Google reCAPTCHA is a CAPTCHA system that support web hosts distinguish between human and bot access to web pages. In the earlier version of Google reCAPTCHA, the user is need to select a checkbox in the CAPTCHA widget. This checkbox attribute is removed in the current of reCAPTCHA. The reCAPTCHA v3 improve the user experience where spam protection can be expanded across the website instead of limited to the particular web form or pages.

Google reCAPTCHA v3 allow the protection of web forms from getting spam. You can verify to check if an engagement is legitimize without any user interaction using reCAPTCHA v3. The user is not required to do any exercise to confirm that they are not a robot. The reCAPTCHA API will identify fraud access and stop bots to avoid automated attacks on the website. In this article, I will show you how to integrate Google reCAPTCHA v3 in HTML form using PHP.

In the tutorial code, the given functionality will be applied to show the Google reCAPTCHA v3 integration with PHP.

  • Generate an HTML form to submit a contact request.
  • Integrate reCAPTCHA v3 API and attach it to the form.
  • Validate request by verifying the user’s action with Google reCAPTCHA API.
  • Fetch form data and send contact request by email using PHP.

Generate reCAPTCHA v3 API Keys

The reCAPTCHA keys need to call the Google reCAPTCHA API. Ahead adding the reCAPTCHA v3 widget to a web page, we need to register your website and get reCAPTCHA API keys.

Register a new site:
Register reCAPTCHA v3 keys on to Google reCAPTCHA Admin console.

  • Label – Make it improved for you to identify the site in the future.
  • reCAPTCHA type – Select reCAPTCHA (version 3) as v3 .
  • Domains – Define the domain of the website.

Click SUBMIT to proceed.

Get Site Key and Secret Key:

After the site submission, your site will be registered with reCAPTCHA v3 and the API keys will be created. The Secret Key and Site Key need to be defined in the script at the time of call Google reCAPTCHA API.

  • Site Key – This key is used in the HTML code of the client-side script.
  • Secret Key – This key helps to allow connection between your site and the reCAPTCHA server and is used in the server-side script for the user’s response verification.

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

Add reCAPTCHA v3 in the HTML Form


The reCAPTCHA v3 does not cut off the user and the widget is adding to the bottom-right corner of the web page. So, you can link reCAPTCHA v3 to any action and run it any time 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 predetermined features to the HTML button, so that reCAPTCHA API will link the challenge automatically to this button.

  • Define the Site Key of the reCAPTCHA v3 in the data-sitekey attribute.
  • Define 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 coding example to integrate reCAPTCHA v3 to form.

  • The reCAPTCHA challenge will link to the submit button.
  • The response token will send 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

When the form submission, the reCAPTCHA challenge will be submitted to the application’s back-end to verify the user’s response and process the contact request.

  • Certify form input fields to check whatever the user fills in the correct values.
  • Apply g-recaptcha-response POST parameter to catch the user response token from the client side script.
  • Implement a cURL request to verify the response token with reCAPTCHA API using PHP.
  • Permit the Site Secret Key (secret), response token (response), and user IP (remoteip) in $_POST parameters.
  • If the reCAPTCHA response is valid and successful, process the contact form submission request furthermore. In another way, show 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 = ''; 
$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(isset($_POST['g-recaptcha-response']) && !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  
            );  
  
            $ch = curl_init();  
            curl_setopt_array($ch, $curlConfig);  
            $response = curl_exec($ch);  
            curl_close($ch);  
  
            // Decode JSON data of API response in array  
            $responseData = json_decode($response);  
  
            // If the reCAPTCHA API response is valid  
            if($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 = '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 given code in the HTML form to display the form submission status message at the clientside script.

<?php if(!empty($statusMsg)){ ?>
    <p class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>


Like it? Share with your friends!

0
Developer

0 Comments