Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Avoid Spam Using hCaptcha

Asyraf Wahi Anuar Updated 2 min read

Integrate hCaptcha with CakePHP 4 to protect unauthorized data submission from bots. Preventing spam in CakePHP 4 form.

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

CAPTCHA (Completely Automated Public Turing Test To Tell Computers and Humans Apart) is used to protect unauthenticated form submission from automated script abuse. Captcha is usually used in the registration form, contact form and other publicly accessible forms. Captcha is considered one of the best methods to recognize whether the end-user is a human or a robot. Captcha can be in form of text-based, mathematical-based, image-based, 3D etc. There are many Captcha providers eg: hCaptcha ; Google reCaptcha; Captchas.net; Jcaptcha etc. This tutorial will show how to implement hCaptcha in CakePHP 4.

hCaptcha Registration

To use the hCaptcha services, the developer needs to register an account with hCaptcha. Click here to create hCaptcha account. Once you create the account and configure site, you will get the site key and secret key (check in your configuration).

Form View

In your form view, eg: add.php, add the following code to load the hCaptcha API JS.

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

Then, at the end of the form, add the following code to render the hCaptcha box. Replace the ‘YourSecretKey’ with your key.

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

Controller

In the controller, add HTTP client to communicate with hCaptcha web service and remote API’s.

PHP
use Cake\Http\Client;

Then add the following code (add method). Change the ‘YourSecretKey’ with your key.

PHP
public function add()
{
    $document = $this->Documents->newEmptyEntity();
    if ($this->request->is('post')) {
        $hcaptcha = $this->request->getData('h-captcha-response');
        $httpClient = new Client();
        $response = $httpClient->post('https://hcaptcha.com/siteverify', [
            'secret' => 'YourSecretKey',
            'response' => $hcaptcha,
        ]);
        $hCaptchaResult = $response->getJson();
        if ($hCaptchaResult['success']) {
            $document = $this->Documents->patchEntity($document, $this->request->getData());
            if ($this->Documents->save($document)) {
                $this->Flash->success(__('The document has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
        } else {
          $this->Flash->error(__('Captcha not fill'));
        }

        $this->Flash->error(__('Unable to save. Please, try again.'));
    }
    $this->set(compact('document'));
}

That’s all. Happy coding :)

Did this tutorial help?

200 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

CakePHP 4 Captcha Plugin

Applying CakePHP Captcha Plugin to web application project. Captcha is a simple solution to block unwanted bot responses to your public available form.

3 min read

CakePHP

Using Bahasa Melayu Table Names in CakePHP

Learn how to use Bahasa Melayu table names like "pengguna" in CakePHP while following the framework’s naming conventions. Includes tips for using the Bake tool and avoiding pluralization issues.

5 min read