Wednesday, September 30, 2009

Secure your forms with Zend_Captcha captcha

Zend_Captcha_Image example

While I'm working with my small project I'm testing various Zend Framework libraries. Today I would show how you can add captcha to your site using Zend_Captcha_Image. In next part of this post I would show how to implement reCAPTCHA with Zend_Captcha.

I have a form class with variuos fields, to secure this class I would use Zend_Captcha_Image library. First should be created Zend_Captcha_Image object and set to it some parameters:

class Form_MyForm extends Zend_Form
public function init ()
//other form elements
// ....

//Captcha element
$captcha = new Zend_Captcha_Image();
//add font for your captcha
$captcha->setFont('../../public_html/images/fonts/font'.rand(1, 14).'.ttf');
//add image dir where your temproary captcha would be stored
$captcha->setWordlen(5); //captvha word length
$captcha->setDotNoiseLevel(0); //set image noise level
$captcha->setLineNoiseLevel(2); //set image line noise level

//set captcha options for form element
$capOptions = array(
'captcha' => $captcha,
'captchaOptions' => array('captcha' => 'Image')

//create form element
$this->captcha = new Zend_Form_Element_Captcha('captcha', $capOptions);
$this->captcha->setLabel('Security Code');

Here is detailed steps of creating captcha:
1. Create instance of Zend_Captcha_Image
2. Set font. You can add multiple fonts and randomize them how is shown in my snippet for even more secure form.
3. Set destination where temporary generated images should be stored.
4. Set captcha code word length 5-8 I think is best.
5. Set captcha image dot noise level in my example it is turned off.
6. Set captcha image line noise level in my example it set to 2.
7. Create array of options for Zend form element object.
8. Finaly create Zend_Form_Element_Captcha object like regular form element.

No comments:

Post a Comment