A Guide on hCaptcha Integration with PHP

Recently one of our readers asked about hCapctha integration on a website. The hCaptcha is a nice alternative to the Google reCAPTCHA service. In this article, we study how one can add hCapctha with PHP on their website.

It is always recommended to have a captcha on the website forms. The spams are really bad and it just frustrates you. You never wish to waste your valuable time in clearing fake/unnecessary comments.

Using hCaptcha, the user has to resolve the challenges before submitting a form. And your form should proceed only if the captcha passes its verification. Integrating a captcha saves a ton of spam from entering into the database and your inbox. Because only a real human can solve the puzzles of the captcha.

Having said that, let’s take a look at integrating hCaptcha with PHP. It requires verifying the hCaptcha response on the server side. We will write the server-side code using both cURL and Guzzle library. The user can use any one of them.

Getting Started

You need to first create an account with hCaptcha service. Unlike Google reCAPTCHA, you can use hCaptcha keys directly on your website. You don’t need to register your domain with them.

But if you wish, you can add your domain by clicking on the +New Site button. It will open a form where you have to pass your domain to the Hostnames field.

Next, click on the settings icon from the table and grab your site key.

hcaptcha-sitekey

To grab the secret key, click on the ‘Settings’ tab.

hcaptcha-secretkey

Once you are ready with keys, there are 2 steps required to follow. First, add the hCaptcha on your form. And then validate the captcha response on the server side.

Let’s create a simple form and add hCaptcha to it as follows.

<form action="" method="POST">
    <input type="text" name="email" placeholder="Email" />
    <input type="password" name="password" placeholder="Password" />
    <div class="h-captcha" data-sitekey="YOUR_SITE_KEY"></div>
    <br />
    <input type="submit" name="submit" value="Submit" />
</form>
<script src="https://hcaptcha.com/1/api.js" async defer></script>

Here we have included hCaptcha’s JavaScript library and added a class h-captcha to the div container. You also need to pass your site key to the data attribute data-sitekey.

Reload the page and you should now see the hCaptcha checkbox added to the form. Let’s see now how to validate the captcha response.

Validate hCaptcha Response using cURL

When a user submits a form along with a captcha, you need to verify the captcha response on the server side. For verification, you have to send POST requests to the hCaptcha’s endpoint https://hcaptcha.com/siteverify. In the POST request, the parameters are the secret key and h-captcha-response(which comes from the submitted form).

In PHP, we can use both cURL and Guzzle to interact with the external server. While sending requests through cURL make sure the cURL extension is enabled on your server.

In the case of cURL, your code will be as follows to verify hCaptcha response.

<?php
if ( isset($_POST['submit']) ) {
    $data = array(
        'secret' => "YOUR_SECRET_KEY",
        'response' => $_POST['h-captcha-response']
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://hcaptcha.com/siteverify");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    $responseData = json_decode($response);
    if($responseData->success) {
        // proceed the form
    } else {
        echo 'Robot verification failed, please try again.';
    }
}
?>

Replace the placeholder with the actual value. In the above code, we are checking if the success variable is true in the response. If it is true then the form is safe to proceed.

Validate hCaptcha Response using Guzzle

Guzzle is an alternative to cURL. It provides a much cleaner code compared to cURL. If you are using Guzzle, you don’t need to have a cURL extension on your server.

To get started, you need to first install the Guzzle library to your project. Run the below command for the installation of a library.

composer require guzzlehttp/guzzle

After this, write the code below which will verify the hCAPTCHA response using the Guzzle library.

<?php
require_once 'vendor/autoload.php';

use GuzzleHttp\Client;

if ( isset($_POST['submit']) ) {

    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'https://hcaptcha.com',
    ]);
     
    $response = $client->request('POST', '/siteverify', [
       'form_params' => [
            'secret' => "YOUR_SECRET_KEY",
            'response' => $_POST['h-captcha-response']
       ]
    ]);

    $body = $response->getBody();
    $arr_body = json_decode($body);
    if($arr_body->success) {
        // proceed the form
    } else {
        echo 'Robot verification failed, please try again.';
    }
}
?>

I hope you understand hCaptcha integration with PHP using cURL and Guzzle. Please share your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

3 thoughts on “A Guide on hCaptcha Integration with PHP

Leave a Reply

Your email address will not be published. Required fields are marked *