09 May

Captcha Validation with 2 lines in CakePHP

Best Practices, CakePHP

Just wrote a captcha validator tool - behavior & a helper to implement captcha quite fast. Here's what you'll do to add captcha verification:

In your controller, lets say I need captcha in registration form.

users_controller.php

PHP:
  1. Function register()
  2. {
  3.         $this->pageTitle ='User Registration';
  4.         // goes on…
  5.         $this->User->enableCaptcha()// this function will initialize the captcha code
  6. }

In the view, register.ctp

PHP:
  1. <?php echo $form->create('User', array('action'=>'register', 'enctype' => 'multipart/form-data'))?>
  2.         <?php echo $form->input('first_name');?>
  3.         <?php echo $form->input('last_name');?>
  4.          <?php echo $form->input('email');?>
  5.         <?php echo $form->input('password', array('type' => 'password'))?>
  6.         <? // line below will generate the image and the input field as well ?>
  7.         <?php echo $captcha->show($this);?>
  8.         <?php echo $form->submit('Register');?>
  9.     </form>

After data is posted through the form, it goes to beforeSave() of my behavior which takes care of the validating and showing up the error in case.

This is the part of my UserContent behavior which will have some more cool shortcuts. Will post them in a while..

- Abhimanyu Grover

Leave A Reply