How to Add BotDetect PHP CAPTCHA Protection to CakePHP 3.0 Applications (BotDetect v3.0; deprecated)

Adding BotDetect PHP Captcha protection to your CakePHP MVC applications requires a slightly different approach than adding it to basic PHP websites, but is still straightforward. This page will guide you through the necessary steps and explain the available options.

First Time Here?

Check the BotDetect CakePHP 3.0 Captcha Quickstart for key integration steps.

Prerequisites

Table of Contents

The BotDetect CakePHP CAPTCHA Integration Package

CakePHP is a MVC framework that leverages certain conventions to provide a rich set of functionality to PHP application developers. Therefore adding BotDetect Captcha into CakePHP based site or application requires a layer of integration code to conform to those conventions. This enables BotDetect Captcha to integrate seamlessly and be used according to expectations of CakePHP developers.

Path Aliases Used Throughout This Guide

  • <MY_CAKE_WEBROOT>: the root of the application install (same as the ROOT PHP CakePHP constant)
  • <BD_CAKE_PACK>: the downloaded and extracted contents of the BotDetect CakePHP Captcha Integration Package

For convenience purposes we are providing the BotDetect Captcha CakePHP integration code packaged as a CakePHP composer plugin.

The BotDetect CakePHP CAPTCHA Composer Plugin

BotDetect CakePHP CAPTCHA composer plugin, is available at https://packagist.org/packages/captcha-com/cakephp-captcha

The integration package includes a wrapper class around the regular BotDetect Captcha Library for use in your application Controllers.

The package also includes separate Controllers that handle:

  • Captcha image and sound requests, which use
    http://<MY_CAKE_WEBROOT>/captcha_handler Urls by default.
  • Captcha resources, which use
    http://<MY_CAKE_WEBROOT>/captcha_resource/get Urls by default.

CakePHP Basic BotDetect CAPTCHA Example

This basic CakePHP 3.0 Captcha example shows how to use the BotDetect Captcha CakePHP composer plugin in your Controller and View code, and handling of basic Captcha user input validation.

  • Controller: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /src/Controller/ExampleController.php
  • View: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /src/Template/Example/index.ctp
  • Captcha configuration options: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /config/captcha_config/ExampleCaptchaConfig.php

Form Model Validation BotDetect CakePHP CAPTCHA Example

This CakePHP 3.0 form model validation Captcha example shows how to use BotDetect Captcha with CakePHP form and validation functionality by implementing a simple contact form.

  • Controller: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /src/Controller/ContactController.php
  • View: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /src/Template/Contact/index.ctp
  • Captcha configuration options: <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples /config/captcha_config/ContactCaptchaConfig.php

CakePHP Auth BotDetect CAPTCHA Example

This CakePHP 3.0 Auth Captcha example shows how to use BotDetect Captcha with CakePHP Auth Component

  • Controller:
    • <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples/src/Controller /UsersController.php
  • View:
    • <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples/src/Template/Users /login.ctp
    • <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples/src/Template/Users /register.ctp
  • Captcha configuration options:
    • <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples/config /captcha_config/LoginCaptchaConfig.php
    • <BD_CAKE_PACK>/bd-captcha-cakephp-3.0-examples/config /captcha_config/RegisterCaptchaConfig.php

The provided examples are available inside of a single CakePHP app via their respective controllers:

   http://<MY_CAKE_WEBROOT>/example
   http://<MY_CAKE_WEBROOT>/contact
   http://<MY_CAKE_WEBROOT>/users/login
   http://<MY_CAKE_WEBROOT>/users/register

You can copy the whole preconfigured CakePHP app from the BotDetect Captcha CakePHP Package somewhere on your development web server and examine it there.

1. Include BotDetect CAPTCHA in Your CakePHP MVC Application

Install BotDetect CakePHP CAPTCHA composer plugin via Composer

Note: If you do not have Composer yet, you can install it by following the instructions on https://getcomposer.org

If you have Git installed on your development machine, you should use the following installation procedure:

Step 1: Install the BotDetect CakePHP Captcha Composer Plugin:

Run the following command in your application's root directory:

Step 2: Load the BotDetect CakePHP Captcha Composer Plugin in your application's bootstrap (<MY_CAKE_WEBROOT>/config/bootstrap.php):

Plugin::load('CakeCaptcha', ['routes' => true]);

A Note On PHP Session Persistence

The BotDetect Captcha Library requires persistent per-user server storage to work properly. By default, it uses standard PHP Sessions, which is convenient in most use cases.

If your environment requires a different approach to handling Session data, you can implement your own Captcha persistence methods via the provided BotDetect Captcha persistence hooks.

The CakePHP BotDetect CAPTCHA composer package integration wrapper executes session_start() when it's called. This provides a safe default that works in most usage scenarios.

If your CakePHP application is handling Sessions in a non-standard way (i.e. there is no PHP $_SESSION available), you can implement your own Captcha persistence methods via provided BotDetect Captcha persistence hooks.

2. Display BotDetect CAPTCHA In Your CakePHP View

Before displaying Captcha in your View, the related Controller needs to import the BotDetectCaptcha class and then create an instance of the Captcha class and set a proper name for your Captcha instance. It also needs to pass a Captcha markup to the View, which can then display it alongside other form elements.

Import the BotDetect CAPTCHA class and create an instance

<?php namespace App\Controller;

use App\Controller\AppController;
// Importing the BotDetectCaptcha class
use CakeCaptcha\Integration\BotDetectCaptcha;

class ExampleController extends AppController
{
    // get captcha instance to handle for the example page
    private function getExampleCaptchaInstance() {
        // Captcha parameters
        $captchaConfig = [
          'CaptchaId' => 'ExampleCaptcha', // a unique Id for the Captcha instance
          'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
           // The path of the Captcha config file is inside the config folder
          'CaptchaConfigFilePath' => 'captcha_config/ExampleCaptchaConfig.php',
        ];
        return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
    }

}

When creating an instance of the Captcha class, it will be supplied a unique name through the CaptchaId setting. Each individual Controller action including Captcha validation should use a unique CaptchaId value to avoid name clashes when persisting.

The additional UserInputId setting is used to setup client-side functionality operating on the Captcha code input field.

You may wish to override library settings, e.g. change a captcha code length, a captcha image style or a captcha image size, or even set your own session mechanism hooks, etc... In order to do that, you'll need to add CaptchaConfigFilePath setting and then provide the path to your Captcha config file. This configuration file MUST be located inside the config folder. For the purpose of this example we have placed it in the captcha_config subfolder, but it may be placed in any subfolder inside the config folder.

Captcha configuration options

<?php if (!class_exists('CaptchaConfiguration')) { return; }

// BotDetect PHP Captcha configuration options

$LBD_CaptchaConfig = CaptchaConfiguration::GetSettings();

$LBD_CaptchaConfig->CodeLength = 5;
$LBD_CaptchaConfig->ImageWidth = 250;
$LBD_CaptchaConfig->ImageHeight = 50;

In the code above, we have overridden the default settings of library (/config/captcha_config/ExampleCaptchaConfig.php). You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

Pass the BotDetect CAPTCHA HTML Markup to the CakePHP View

The CakePHP MVC Captcha composer plugin generates its own markup, which should be made available to your View. The Captcha Html is retrieved by calling the Html() method on the $captcha object. It is then made available to the view by setting a variable with Controller::set().

<?php namespace App\Controller;

use App\Controller\AppController;
// Importing the BotDetectCaptcha class
use CakeCaptcha\Integration\BotDetectCaptcha;

class ExampleController extends AppController
{
    // get captcha instance to handle for the example page
    private function getExampleCaptchaInstance() {
        // Captcha parameters
        $captchaConfig = [
          'CaptchaId' => 'ExampleCaptcha', // a unique Id for the Captcha instance
          'UserInputId' => 'CaptchaCode', // Id of the Captcha code input textbox
          // The path of the Captcha config file is inside the config folder
          'CaptchaConfigFilePath' => 'captcha_config/ExampleCaptchaConfig.php', 
        ];
        return BotDetectCaptcha::GetCaptchaInstance($captchaConfig);
    }

    public function index() {
        // captcha instance of the example page
        $captcha = $this->getExampleCaptchaInstance();

        // passing Captcha Html to example view
        $this->set('captchaHtml', $captcha->Html());
    }
    
}

The Captcha markup is now available inside your View's $captchaHtml variable.

Display BotDetect CAPTCHA in Your CakePHP App's View

Inside your View script, you should include some form elements alongside the Captcha display. In a regular form with a submit button, you need an input field where the user retypes the characters rendered in the Captcha image.

To display Captcha image you should output the $captchaHtml variable from the previous step:

<?= $this->Form->create(null, ['url' => ['controller' => 'example', 
  'action' => 'index']]) ?>

<?= $captchaHtml ?>
<?= $this->Form->input('CaptchaCode', [
    'id' => 'CaptchaCode'
  ]
) ?>

<?= $this->Form->button(__('Submit')); ?>
<?= $this->Form->end() ?>

You'll also need to add the BotDetect Captcha layout stylesheet, which CakePHP will include in the <head> of your page containing the Captcha:

<?= $this->Html->css(CaptchaUrls::LayoutStylesheetUrl(), ['inline' => false]) ?>

BotDetect Captcha should now be visible in your App's View.

3. Validate the CAPTCHA In Your CakePHP Controller

After your Captcha is displayed alongside a form input field, you will want to validate user submitted Captcha code in a Controller action. This should always be done before any sensitive processing to confirm the submitted data is actually entered by a person and not a bot.

Validate the Submitted CAPTCHA Code User Input

The validation of Captcha code input should be performed in Controler->Action that is on the receiving end of the form submission (where the form action points to).

Usually, the submitted form data is available inside the CakePHP request object, by the same name you gave the Captcha code input field on the form where it was displayed. For example: $this->request->data['CaptchaCode'].

It is then a matter of calling the Validate() method of the Captcha object and passing it the user input.

// captcha instance of the example page
$captcha = $this->getExampleCaptchaInstance();
// assuming "CaptchaCode" input field id
$isHuman = $captcha->Validate($this->request->data['CaptchaCode']);

unset($this->request->data['CaptchaCode']);

Handle CAPTCHA Validation Failure / Success

You should then write some code to handle both Captcha validation success and failure. If it failed, you should abort further processing and display an error message; if it succeeded, you can proceed with the protected form action:

if ($isHuman) {
  // TODO: Captcha validation passed:
  // continue with form processing, knowing the submission was made by a human
} else {
  // TODO: Captcha validation failed:
  // abort sensitive action, return an error message
}

This will ensure that the sensitive action can not be automated and is only performed when a human fills out the form.



Please Note

The information on this page is out of date and applies to a deprecated version of BotDetect™ CAPTCHA (v3.0).

An up-to-date equivalent page for the latest BotDetect Captcha release (v4) is BotDetect v4 Captcha documentation index.

General information about the major improvements in the current BotDetect release can be found at the What's New in BotDetect v4.0 page.