Integrate CAPTCHA Checkbox with hCaptcha using PHP

CAPTCHA is a verification process to determine whether the user is a human or not. Generally, the CAPTCHA is used in the web form to prevent spam submission. Without a CAPTCHA, the bots can submit spam information by automated form submission that fills your site with just data. Adding CAPTCHA to the website, always a good idea to prevent spam in the web form.

Different types of Captcha can be used for the verification process, like questions, number calculation, checkbox, etc. Before form submission, the user must solve the CAPTCHA and prove that they are not a robot. You can easily integrate CAPTCHA functionality in the web form using PHP. If you want to provide a user-friendly way, checkbox Captcha is the best option.

To make the CAPTCHA integration process simple and secure, you can use third-party API. The hCaptcha provides a quick and easy way to add CAPTCHA to the webform using PHP. The hCaptcha is the best alternative of Google reCAPTCHA Checkbox. In this tutorial, we will show you how to integrate CAPTCHA functionality with hCaptcha using PHP.

Generate hCaptcha API Keys

The Site and Secret keys are required to use the hCaptcha API. Before adding the CAPTCHA checkbox to your site, you need to register your site and get the API keys.

  • Visit hCaptcha site and register your account.
  • Log into your account and click on the + New Site button.
    • Name – Help to identify your registered site in the future.
    • Hostnames – Specify the domain of your website.

php-captcha-with-hcaptcha-api-site-domain-register-codexworld-1024x671.png

  • Click Save to register your site.
  • The added site will be listed under the Sites tab. You will see the Sitekey by clicking the Settings button.

php-captcha-with-hcaptcha-api-site-key-codexworld-1024x218.png

  • Under the Settings tab, you will see the Secret key.

php-captcha-with-hcaptcha-api-secret-key-codexworld-1024x427.png

Copy the Site Key and Secret Key for later use in the PHP CAPTCHA integration code.

Add hCaptcha Widget to HTML Form

At first, include the JavaScript library of hCaptcha API.

<script src="https://hcaptcha.com/1/api.js" async defer>script>

Add the h-captcha tag element in the HTML form where you want to display the hCaptcha checkbox widget.

  • The h-captcha DIV element has a class named h-captcha and data-sitekey attributes.
  • The Site Key of the hCaptcha API will be specified in the data-sitekey attribute.

<form action="" method="post">
    <div class="input-group">
        <input type="text" name="name" value="" placeholder="Your name" required="" />
    div>
    <div class="input-group">	
        <input type="email" name="email" value="" placeholder="Your email" required="" />
    div>
    <div class="input-group">
        <textarea name="message" placeholder="Type message...">textarea>
    div>
		
    
    <div class="h-captcha" data-sitekey="Your_hCAPTCHA_Site_Key">div>
	
    
    <input type="submit" name="submit" value="SUBMIT">
form>

Verify hCaptcha Response (Server-side Validation)

After the form submission, the input data will be submitted to the server-side script to verify the user’s response and process the form submission request.

  • Validate form fields to check whether the user fills the required input fields.
  • Use the h-captcha-response POST parameter to check whether the user selects the CAPTCHA checkbox.
  • Verify the CAPTCHA challenge using hCaptcha and PHP.
    • Initialize PHP cURL request and POST required params to hCaptcha API.
      • secret – Secret Key
      • response – The user’s response received by $_POST['h-captcha-response'].
      • remoteip – The user’s IP address.
  • Parse JSON from hCaptcha response and check for status.
  • If the hCaptcha response is valid and successful,
    • The form is submitted.
    • The status message is shown to the user.
 
// hCAPTCHA API key configuration
$secretKey 'Insert_hCaptcha_Secret_Key';

// If the form is submitted
$statusMsg '';
if(isset(
$_POST['submit'])){
    
    
// Validate form fields
    
if(!empty($_POST['name']) && !empty($_POST['email'])){
        
        
// Validate hCAPTCHA checkbox
        
if(!empty($_POST['h-captcha-response'])){
            
// Verify API URL
            
$verifyURL 'https://hcaptcha.com/siteverify';
            
            
// Retrieve token from post data with key 'h-captcha-response'
            
$token $_POST['h-captcha-response'];
            
            
// Build payload with secret key and token
            
$data = array(
                
'secret' => $secretKey,
                
'response' => $token,
                
'remoteip' => $_SERVER['REMOTE_ADDR']
            );
            
            
// Initialize cURL request
            // Make POST request with data payload to hCaptcha API endpoint
            
$curlConfig = array(
                
CURLOPT_URL => $verifyURL,
                
CURLOPT_POST => true,
                
CURLOPT_RETURNTRANSFER => true,
                
CURLOPT_POSTFIELDS => $data
            
);
            
$ch curl_init();
            
curl_setopt_array($ch$curlConfig);
            
$response curl_exec($ch);
            
curl_close($ch);
            
            
// Parse JSON from response. Check for success or error codes
            
$responseData json_decode($response);
            
            
// 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']:'';
                
                
// Code to process the form data goes here...
                
                
                
$statusMsg 'Your contact request has submitted successfully.';
            }else{
                
$statusMsg 'Robot verification failed, please try again.';
            }
        }else{
            
$statusMsg 'Please check on the CAPTCHA box.';
        }
    }else{
        
$statusMsg 'Please fill all the mandatory fields.';
    }
}

echo 
$statusMsg;

?>

Related Articles

Comments 0