How to add hCaptcha in PHP forms with live example

Abhigyan Singh 24th Nov 2020

In this tutorial, we will show you how to add hCaptcha in PHP forms. hCaptcha is the most growing CAPTCHA service which is the best and only one alternative of Google reCaptcha.

As we know that Google reCaptcha is a widely used captcha service to prevent any kind of spambot or abuse in your website. So we have also created a tutorial to integrate Google reCaptcha v2 and Google reCaptcha v3 in PHP. If you still want to integrate Google reCaptcha in your application, then you can follow the below tutorial.

Add Google reCAPTCHA V3 in PHP contact form with live demo

Integrate Google reCAPTCHA v2 in PHP with example

Now let’s dive into the hCaptcha implementation

Introduction of hCaptcha

hCaptcha is the most growing and widely used free captcha service which prevents your website from any spam attack. hCaptcha is very easy to use in your application which we will see in the below article so please read this article at the end.

It is also an alternative to Google reCaptcha. You can easily change your Google reCaptcha with hCaptcha without much changes in the code. You can follow these steps to switch from reCAPTCHA to hCaptcha.

hCaptcha works on the models of machine learning to identify whether the user is a bot or a real human. So the answer is parsed by a machine learning algorithm and provides the correct answer.

Get reward or earn money while using hCaptcha

You can also earn rewards for every correct answer. hCaptcha is basically creating their database with the help of our provided answers so they are giving some reward based on the correctness of the answers.

It calculates on the real time estimation of total number of solved captchas with some other parameter and calculates your earnings.

You can directly receive the amount by PayPal account once your amount is reached the minimum threshold value.

You can click here to create your free account of hCaptcha today and earn rewards.

Now we will see to integrate hCaptcha with the help of a simple login form in PHP.

How to add hCaptcha in PHP form

We have already used the contact form to demonstrate the integration of Google reCaptcha so here we will use a simple login form to explain the integration of hCaptcha.

We are just listing all the steps which will use to integrate hCaptcha in PHP.

  • Create an account on hCaptcha website
  • Add your website on which you will use hCaptcha
  • Generate your site key and Secret key
  • Create a simple login form in PHP and add hCaptcha validation code

Create an account on hCaptcha website

First of all, we need to create an account on hCaptcha website. So click here to create hCaptcha account here. You can also log in with your GitHub account.

hCaptcha Website

Here, click on 'Signup' button on the right top corner as shown in the above image. If you have already signup then click on 'Login' button to login into your hCaptcha account.

Add your website on which you will use hCaptcha

Now, its the time to add your website into hCaptcha where you will use the captcha. You can do this by clicking on '+ New Site' button which is shown in the below image.

hCaptcha account 1

The below image will show the complete option and steps to add your site in hCaptcha.

Add site in hCaptcha account

Generate your site key and Secret key for hCaptcha

Once you add your site in hCaptcha account then you will receive site key and secret key to use it in your application.

Site Key: This key will use in HTML form to generate post value for hCaptcha. You can check it in the browser console.

Secret Key: This key will use on server side to validate the form data and get the response from hCaptcha server.

Create a simple login form in PHP and add hCaptcha validation code

Now we will create two file to show the implementation of hCaptcha

  1. Index.php
  2. do_login.php

index.php: In this file, we create a simple login form and include one Js file and one hidden field.

The included Js file:

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

The hidden field named 'h-captcha'. Here we need to replace your generated hCaptcha site key.

<div class="h-captcha" data-sitekey="<YOUR_SITE_KEY>"></div>

The complete code of the index.php is given below:

<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Google reCapctha Example</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
      <script src="https://hcaptcha.com/1/api.js" async defer></script>
   </head>
   <body>
      <div class="container col-sm-5" style="background-color:#ffffff; padding:25px; border: 1px solid #d9d8d8;">
         <form action="" method="post">
         <div id="alert_message"></div>
            <div class="form-group">
               <label for="email">Email:</label>
               <input type="text" class="form-control" id="email_id" placeholder="Enter your Email" name="email_id" required>
            </div>
            <div class="form-group">
               <label for="pwd">Password:</label>
               <input type="text" class="form-control" id="password" placeholder="Enter your Password" name="password" required>
            </div>
            <div class="h-captcha" data-sitekey="<YOUR_SITE_KEY>"></div>
            <input type="submit" name="submit" value="Submit" class="btn btn-success btn-lg" style="padding: 6px 46px; margin: 16px 0 0 0;">
            <div style="font-size: 12px; padding-top: 12px; color: #808080;">Note: This form is protected by hCaptcha.</div>
         </form>
      </div>
      <script>
        $('form').submit(function(event) {
            event.preventDefault(); //Prevent the default form submission

           // Making the simple AJAX call to capture the data and submit
           $.ajax({
                        url: 'do_login.php',
                        type: 'post',
                        data: $('form').serialize(),
                        dataType: 'json',
                        success: function(response){
                            var error = response.error;
                            var success = response.success;
                            if(error != "") {
                                $('#alert_message').html(error);
                            }
                            else {
                                $('#alert_message').html(success);
                            }
                        },
                        error: function(jqXhr, json, errorThrown){
                            var error = jqXhr.responseText;
                            $('#alert_message').html(error);
                        }
                    });
   });
    </script>
   </body>
</html>

We have created a simple login form from the above script. Now let's capture the data from this form and validate it from the below script. Here, we will use a previously generated secret key.


<?php
function is_entered_data_valid() {
    // This is just a basic type of validation for demo purpose. Replace this with your own server side validation
    if($_POST['email_id'] != "" && $_POST['password'] != "") {
        return true;
    } else {
        return false;
    }
}
if(is_entered_data_valid()) {
    if(isset($_POST['h-captcha-response']) && !empty($_POST['h-captcha-response'])){
        $secret = "<YOUR_SECRET_KEY>"; // Replace it with your generated secret key
        $remote_address = $_SERVER['REMOTE_ADDR'];
        $verify_url = "https://hcaptcha.com/siteverify?secret=".$secret."&response=".$_POST['h-captcha-response']."&remoteip=".$remote_address;
            // This is hcaptcha url
        $response = file_get_contents($verify_url); # Get token from post data with key 'h-captcha-response' and Make a POST request with data payload to hCaptcha API endpoint
        $responseData = json_decode($response);
        $success_msg="";
        $err_msg="";
        if($responseData->success){
            $success_msg = "You can process your login functionality";
        }else{
            $err_msg =  "Something went wrong while hCaptcha Validation. Please try again after sometime.";
        }
    }else{
        $err_msg =  "Please fill all the required fields";
    }
} else {
    // Server side validation failed
    $error_output = "Please fill all the required fields";
}
// Get the response and pass it into your ajax as a response.
$return_msg = array(
    'error'     =>  $err_msg,
    'success'   =>  $success_msg
 );
 echo json_encode($return_msg);
?>

Here, you need to replace your secret key and validate the response given from the hCaptcha API. If the output or response of $responseData is a success, you can process your login functionality.

We have not covered the complete login functionality in this tutorial because our purpose is just to show the hCaptcha integration in PHP with the help of login form.

Hope you will not find any difficulties while adding hCaptcha in your application. We have already created a working code that can be easily downloaded from GitHub repository. Still, if you have any query regarding this tutorial, you can feel free to reach us.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

Also on DiscussDesk