CakePHP 2 Basic BotDetect CAPTCHA Example

This code example illustrates the most basic form of BotDetect PHP Captcha protection in CakePHP MVC applications.

First Time Here?

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

Alongside the Captcha image, the user is provided with an input field to retype the displayed characters. Depending on if the Captcha code entered matches the displayed one or not, a message stating the validation result is shown on the form.

The simple code showing the message in this example would of course be replaced with useful form processing code in a real world scenario.

BotDetect CakePHP 2 CAPTCHA basic Captcha validation screenshot

Files for this ('bd-captcha-cakephp-2-examples') example are:

The files are available for download as a part of the BotDetect Captcha CakePHP integration package.

Config – /config/captcha.php

<?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, we have declared Captcha configuration which will be used when loading Captcha component in ExampleController. Detailed description of this approach is available in a BotDetect CakePHP 2 integration guide.

View – /app/View/Example/index.ctp

<h1>CakePHP Basic BotDetect CAPTCHA Example</h1>

<?php
  // include the BotDetect layout stylesheet
  echo $this->Html->css(captcha_layout_stylesheet_url(), array('inline' => false));

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

  // validation status message
  echo $validationStatus;
?>

The above code uses the CakePHP FormHelper to generate a form, although the actual form can be created in many other ways. The only requirement is that the form contains an input field of your choice where the user can retype the characters shown in the Captcha image. This user-entered code should be available to you in Controller code after form submission.

Note that the action of the form points to the same action of the Controller the View belongs to. Also, the name of the input field corresponds to the variable in the request object that we will use for validation in the Controller.

We display the image by calling the captcha_image_html() helper function. The View utilizes the HtmlHelper::css() method to add the required stylesheet, and it also prints out a message about the Captcha validation status (set in the Controller).

Controller – /app/Controller/ExampleController.php

<?php
App::uses('Controller', 'Controller');

class ExampleController extends Controller {
  public $name = 'Example';
  public $helpers = array('Form', 'Html', 'Js');

  // load the BotDetect Captcha component and set its parameter
  public $components = array(
    'BotDetect.Captcha' => array(
      'captchaConfig' => 'ExampleCaptcha'
    )
  );

  public function index() {
    // initially, the message shown to the visitor is empty
    $this->set('validationStatus', '');

    if ($this->request->is('post')) {

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

      if ($isHuman) {
        // Captcha validation passed
        $this->set('validationStatus', 'CAPTCHA validation passed, human visitor confirmed!');
        // TODO: continue with form processing, knowing the submission was made by a human
      } else {
        // Captcha validation failed, return an error message
        $this->set('validationStatus', 'CAPTCHA validation failed, please try again.');
      }
    }
  }
}

The example Controller follows the basic instructions from the BotDetect CakePHP 2 integration guide.

After loading the required helpers and the BotDetect Captcha CakePHP component, the example form submits the data to the same Controller action that shows it (index), which is where we check the submitted data and pass it to the captcha_validate() helper function.