Code The Pixel

CakePHP 4 Captcha Plugin

Asyraf Wahi Anuar - September 14, 2021
Published in CakePHP 1328 Views Email This Article
Estimated reading time: 1 minute, 39 seconds

CAPTCHA is an acronym that stands for the Completely Automated Public Turing test to tell Computers and Humans Apart. CAPTCHAs are tools that can be used to distinguish between human users and artificial users such as bots. CAPTCHAs present tasks that are tough for machines to complete but relatively simple for people to complete. If you are building any public form in your web application, Captcha is a very useful tool to control the bot from submitting unnecessary responses. The Captcha Plugin enable the developer to apply captcha in any form. 

Requirement
CakePHP 4+
GD Library enable

Download Captcha Plugin
Run any preferred console, then execute the following composer code:

composer require dereuromark/cakephp-captcha


Load Captcha Plugin:

bin/cake plugin load Captcha


or manually load at …src/Application.php

$this->addPlugin('Captcha');


Captcha Database Schema
Execute the following migration command:

bin/cake migrations migrate -p Captcha


Load Captcha Helper

File location: …\src\View\AppView.php
    public function initialize(): void
    {
        $this->loadHelper('Paginator', ['templates' => 'paginator-templates']);
        $this->loadHelper('Captcha.Captcha');
    }


Load Captcha Component
In your controller, add the following code:

    public function initialize(): void
    {
        parent::initialize();
        $this->loadComponent('Paginator');
        $this->loadComponent('Captcha.Captcha', ['actions' => ['add']]);
        $this->viewBuilder()->setHelpers(['Captcha.Captcha' => ['ext' => 'png']]);
    }


Captcha View
To render the captcha, add the following code into your form:

<?php echo $this->Captcha->render(['placeholder' => __('Please solve the riddle')]); ?>


The form will render the captcha (simple math) and required user input before submitting the form response. If you are using the Authentication Plugin, you can use the following code in your controller to activate the Captcha only for an unauthenticated user.

        if (!$this->getRequest()->getAttribute('identity')['id'] ?? null) {
            $this->loadComponent('Captcha.Captcha', ['actions' => ['add']]);
            $this->viewBuilder()->setHelpers(['Captcha.Captcha' => ['ext' => 'png']]);
        }


TIPS: Don’t forget to enable the GD library, or else, your captcha will not be rendered.

That’s all, happy coding :)


Cite this article (APA 6th Edition)