Integrate new Google reCAPTCHA Checkbox with PHP

Generate reCAPTCHA API Keys

Google has launched the new reCAPTCHA v2. Generate reCAPTCHA by using the reCAPTCHA widget, users have a proof that he/she is not a robot without solving a CAPTCHA question. You only need a single click to confirm they are not a robot. The Google reCAPTCHA Checkbox secures your website from spam with a better user experience. Generally, For the webform, for Google reCAPTCHA functionality. But, You have to use the reCAPTCHA to validate any response coming from the website.

Google reCAPTCHA v2 gives you an easy way to secure your web form or web page from getting spam. Google ReCaptcha can be easily integrated into a website using PHP. In this tutorial, we will explain to you how to unify Google reCAPTCHA v2 checkbox with PHP in a web form.

In the instance code, we have implemented the following functionality given below, to demonstrate the Google reCAPTCHA integration with PHP.

reCAPTCHA

Generate reCAPTCHA API Keys: 

Firstly, you need a reCAPTCHA key to call the Google reCAPTCHA API. Before adding a reCAPTCHA v2 checkbox to your Site, you need to register your website and get reCAPTCHA API keys.

Register Website:

Secondly, after the generation, you have to register the domain of your website at Google reCAPTCHA Admin console.

Get Site Key and Secret Key:

 Thirdly, After submitting, It will add your Site. Also, it will generate reCAPTCHA keys. On the other hand, specify the Site Key and Secret Key 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 integration code.

Add reCAPTCHA Widget to HTML Form

First, include the JavaScript library of the reCAPTCHA API. Add the G-Recapta tag element to the HTML form where you want to display the reCAPTCHA checkbox widget.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<!-- Status message -->
<?php if(!empty($statusMsg)){ ?>
    <p class="status-msg <?php echo $status; ?>"><?php echo $statusMsg; ?></p>
<?php } ?>

<form action="" method="post">
    <!-- Form fields -->
    <div class="input-group">
        <input type="text" name="name" value="<?php echo !empty($postData['name'])?$postData['name']:''; ?>" placeholder="Your name" required="" />
    </div>
    <div class="input-group">	
        <input type="email" name="email" value="<?php echo !empty($postData['email'])?$postData['email']:''; ?>" placeholder="Your email" required="" />
    </div>
    <div class="input-group">
        <textarea name="message" placeholder="Type message..." required="" ><?php echo !empty($postData['message'])?$postData['message']:''; ?></textarea>
    </div>
		
    <!-- Google reCAPTCHA box -->
    <div class="g-recaptcha" data-sitekey="Your_reCAPTCHA_Site_Key"></div>
	
    <!-- Submit button -->
    <input type="submit" name="submit" value="SUBMIT">
</form>

Verify reCAPTCHA Response (Server-side Validation)

Finally, after submitting the form, the input data will be provided in a server-side script to validate the user’s response and process the contact request.

<?php 
$postData = $statusMsg = ''; 
$status = 'error'; 
 
// If the form is submitted 
if(isset($_POST['submit'])){ 
    $postData = $_POST; 
     
    // Validate form fields 
    if(!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['message'])){ 
         
        // Validate reCAPTCHA box 
        if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response'])){ 
            // Google reCAPTCHA API secret key 
            $secretKey = 'Your_reCAPTCHA_Secret_Key'; 
             
            // Verify the reCAPTCHA response 
            $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']); 
             
            // Decode json data 
            $responseData = json_decode($verifyResponse); 
             
            // If reCAPTCHA response is valid 
            if($responseData->success){ 
                // Posted form data 
                $name = !empty($_POST['name'])?$_POST['name']:''; 
                $email = !empty($_POST['email'])?$_POST['email']:''; 
                $message = !empty($_POST['message'])?$_POST['message']:''; 
                 
                // Send email notification to the site admin 
                $to = 'admin@example.com'; 
                $subject = 'New contact form have been submitted'; 
                $htmlContent = " 
                    <h1>Contact request details</h1> 
                    <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"; 
                // More headers 
                $headers .= 'From:'.$name.' <'.$email.'>' . "\r\n"; 
                 
                // Send email 
                @mail($to,$subject,$htmlContent,$headers); 
                 
                $status = 'success'; 
                $statusMsg = 'Your contact request has submitted successfully.'; 
                $postData = '';
            }else{ 
                $statusMsg = 'Robot verification failed, please try again.'; 
            } 
        }else{ 
            $statusMsg = 'Please check on the reCAPTCHA box.'; 
        } 
    }else{ 
        $statusMsg = 'Please fill all the mandatory fields.'; 
    } 
} 
?>

Conclusion

Several options are available to add captcha functionality to the website. The easiest option is to add a captcha challenge to form on the Google reCAPTCHA site. Therefore, you can also view the analysis report of CAPTCHA requests in the RECAPTCHA admin panel. In the example code, we have explained how you can add the Google reCAPTCHA v2 checkbox to the contact form.

Also, read our previous blog- Google Invisible reCAPTCHA with PHP

Exit mobile version