CakePHP 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 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 CAPTCHA basic Captcha validation screenshot

Files for this ('cakephp_form_validation_captcha_example') example are:

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

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

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

<?php
  // include the BotDetect layout stylesheet
  echo $this->Html->css(CaptchaUrls::LayoutStylesheetUrl(), 
	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', $captchaHtml, 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.

The helpers and the Captcha markup made available in the Controller are used in the View to compose a simple form with one input field and a Captcha image. 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

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

  // load the BotDetect Captcha component and set its parameters
  public $components = array(
    'BotDetect.Captcha' => array(
      'CaptchaId' => 'ExampleCaptcha', // a unique Id for the Captcha instance
      'UserInputId' => 'CaptchaCode' // Id of the Captcha code input textbox
    )
  );

  public function index() {
    // make Captcha Html accessible to View code
    $this->set('captchaHtml', $this->Captcha->Html());

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

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

      // validate the user-entered Captcha code
      $isHuman = $this->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) {
          $this->set('validationStatus', 'CAPTCHA validation passed, human visitor 
          confirmed!');
        // Captcha validation passed
        // 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 integration guide.

After loading the required helpers and the BotDetect Captcha CakePHP component, the Html required for displaying the Captcha image and integrated controls is made available to the View by using the Controller:set() method.

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 Validate() method of the Captcha component object.