How to Add BotDetect PHP CAPTCHA Protection to CakePHP 2 Applications

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 2 Captcha Quickstart for key integration steps.

Prerequisites

Table of Contents

The BotDetect CAPTCHA CakePHP Download Package

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

Path Aliases Used Throughout This Guide

  • <MYCAKEAPP>: your CakePHP app directory (same as the APP_DIR PHP CakePHP constant)
  • <BDCAKEPACK>: the downloaded and extracted contents of the BotDetect Captcha CakePHP Package

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

You can get the whole BotDetect Captcha CakePHP integration package here. Included in this package is the integration code, a basic Captcha validation example, and a example showing use of BotDetect Captcha with CakePHP FormHelper and model validation.

(The BotDetect Captcha PHP Library is a required and separate download available here.)

The BotDetect CAPTCHA CakePHP Plugin

BotDetect CakePHP Plugin code, sans the Captcha library, is located at <BDCAKEPACK>/plugin/BotDetect.

The code includes a Captcha component for use in your application Controllers, and a separate Controller that handles Captcha image and sound requests. This Captcha Controller uses http://<MYCAKEAPP>/botdetect/captcha-handler Urls by default.

CakePHP Basic BotDetect CAPTCHA Example

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

  • Controller: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/ app/Controller/ExampleController.php
  • View: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/View/Example/index.ctp
  • Config: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/Config/captcha.php

CakePHP Form Model Validation BotDetect CAPTCHA Example

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

  • Controller: <BDCAKEPACK>/bd-captcha-cakephp-2-examples /app/Controller/ContactController.php
  • Model: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/Model/Contact.php
  • View: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/View/Contact/index.ctp
  • Config: <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/Config/captcha.php

CakePHP Auth BotDetect CAPTCHA Example

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

  • Controller:
    • <BDCAKEPACK>/bd-captcha-cakephp-2-examples /app/Controller/UsersController.php
  • View:
    • <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/View/Users/login.ctp
    • <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/View/Users/add.ctp
  • Config:
    • <BDCAKEPACK>/bd-captcha-cakephp-2-examples/app/Config/captcha.php

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

   http://<MYCAKEAPP>/example
   http://<MYCAKEAPP>/contact
   http://<MYCAKEAPP>/users/login
   http://<MYCAKEAPP>/users/add

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

Copy the Necessary BotDetect CAPTCHA Files

BotDetect CakePHP CAPTCHA Plugin folder structure screenshot

The base BotDetect Captcha library and CakePHP MVC Captcha integration code are distributed separately and need to be merged so you can use them in your CakePHP app.

1. BotDetect CakePHP CAPTCHA Plugin

Copy (the whole directory and all contents)
<BDCAKEPACK>/bd-captcha-cakephp-2-examples/ 
app/Plugin/BotDetect
to
<MYCAKEAPP>/Plugin/BotDetect

2. BotDetect CAPTCHA Library Code

Copy (the whole directory and all contents)
<BDCAKEPACK>/bd-captcha-cakephp-2-examples/ 
app/Lib
to
<MYCAKEAPP>/Lib

Load the BotDetect CAPTCHA Plugin in Your CakePHP Application

Your CakePHP app needs to be made aware of the BotDetect Captcha plugin. This is done inside your application's bootstrap (<MYCAKEAPP>/Config/bootstrap.php).

Add this code
CakePlugin::load(array(
 'BotDetect' => array('routes' => true)
));

at the end of your bootstrap.php file.

Please note that the whole MVC Captcha library is not loaded at every request; this is just letting the CakePHP application know about the plugin and leverages Cake's lazy-loading infrastructure to load the BotDetect code when it's actually needed.

That's it. BotDetect Captcha is ready to be used in your CakePHP application.

A Note On PHP Session Persistence

The CakePHP CAPTCHA Plugin requires persistent per-user server storage to work properly. By default, it uses CakePHP Sessions, which is convenient in most use cases.

If your environment requires a different approach to handle Session data, you can be easily adding a custom session driver as described here.

Note that a Session cleanup right after creating a Captcha class instance may cause an error since BotDetect will not find its Session data.

2. Display BotDetect CAPTCHA In Your CakePHP View

Captcha configuration options

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

// BotDetect PHP Captcha configuration options

$config = array(
  // Captcha configuration for example page
  'ExampleCaptcha' => array(
    'UserInputID' => 'CaptchaCode',
    'ImageWidth' => 250,
    'ImageHeight' => 50,
  ),

);

In order to use the CakePHP CAPTCHA Plugin, you must delare Captcha configuration in app/Config/captcha.php file following the structure given above. The ExampleCaptcha is an example name and will be used when loading the BotDetect CakePHP component in your controller. You should pick a name that best matches your usage scenario like: LoginCaptcha, ContactCaptcha, etc. You can find a full list of available Captcha configuration options and related instructions at the Captcha configuration options page.

In case you need different Captcha for another form in your application, here is the example how to add additional captcha configuration for a login form:

<?php
// BotDetect PHP Captcha configuration options

$config = array(
  // Captcha configuration for example page
  'ExampleCaptcha' => array(
    'UserInputID' => 'CaptchaCode',
    'ImageWidth' => 250,
    'ImageHeight' => 50,
  ),

  // Captcha configuration for login page
  'LoginCaptcha' => array(
    'UserInputID' => 'CaptchaCode',
    'CodeLength' => CaptchaRandomization::GetRandomCodeLength(4, 6),
    'ImageStyle' => array(
      ImageStyle::Radar,
      ImageStyle::Collage,
      ImageStyle::Fingerprints,
    ),
  ),

);

Load the BotDetect CAPTCHA CakePHP Component

The BotDetect CakePHP Captcha plugin uses the usual method of loading and configuring components inside of CakePHP.

class ExampleController extends AppController { // your controller
  
  public $components = array(
    'BotDetect.Captcha' => array(
      'captchaConfig' => 'ExampleCaptcha'
    )
  );
}

The BotDetect MVC Captcha component is available in CakePHP code under the BotDetect plugin namespace. It's loaded to the $components array in your Controller, and then assigns it a captcha configuration key defined in app/Config/captcha.php file. Each individual Controller action including Captcha validation should use a unique captchaConfig value to avoid persistence name clashes.

Compose Your CakePHP View With BotDetect CAPTCHA Display

Inside your View's .ctp script, you should include some form elements alongside the Captcha display. You can use either straight markup or the CakePHP FormHelper. In a regular form with a submit button, you need an input field where the user retypes the characters shown in the Captcha image.

You display the image by calling the captcha_image_html() helper function:

echo $this->Form->create(false, array('action' => 'index'));

// display Captcha markup, wrapped in an extra div for layout purposes
echo $this->Html->div('captcha', captcha_image_html(), false);

// Captcha code user input textbox
echo $this->Form->input('CaptchaCode', array(
    'label' => 'Retype the characters from the picture:',
    'maxlength' => '10',
    'style' => 'width: 300px;'
  )
);

echo $this->Form->end('Submit');

You also need to add the BotDetect Captcha layout stylesheet by calling the captcha_layout_stylesheet_url() helper function, which CakePHP will include in the <head> of your page containing the Captcha:

echo $this->Html->css(captcha_layout_stylesheet_url(), array('inline' => false));

The Captcha should now be visible and functioning in your View.

3. Validate the CAPTCHA In Your CakePHP Controller

After your Captcha is displayed alongside a form input field, you will want to validate the user submitted Captcha code in the 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 done in the 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 captcha_validate() helper function and passing it the user input.

// validate the user-entered Captcha code
$isHuman = captcha_validate($this->request->data['CaptchaCode']);

// clear previous user input, since each Captcha code can only be validated once
unset($this->request->data['CaptchaCode']);

After Captcha validation, it is best to clear the previous user input automatically; since each Captcha code can only be validated once regardless of the validation result, keeping previous user input makes no sense.

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.