</> Code The Pixel

CakePHP 4 Captcha Plugin

Asyraf Wahi Anuar - September 14, 2021

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. 

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


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']);

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

    public function initialize(): void
        $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)

CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 Sending Email
February, 01 2022
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Sharing Link
Click the icon to share