Thursday, October 1, 2009

Secure your forms with Zend_Captcha captcha Part 2 reCaptcha


In last post I wrote that I would show you how to use reCaptcha service with your Zend Framework application. To use reCaptcha service you need service public key and private key. To get keys go to reCaptcha website and hit "Use reCAPTCHA on your site" red button on the bottom of the page and signup for free account. After sign up login to your reCaptcha account and create new reCaptcha key simply writing your website address. After creating new key you shoud get private and public keys.

To use reCaptcha with your Zend Framework put reCaptcha keys in config file or difine as constants in your bootsrap file like I did.


define('RECAPTCHA_PRIVATE_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
define('RECAPTCHA_PUBLIC_KEY', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');



Now in you form class create reCaptcha service object and add some options to it:


//crate service object
$recaptcha = new Zend_Service_ReCaptcha(RECAPTCHA_PUBLIC_KEY, RECAPTCHA_PRIVATE_KEY);
//adding option, setting recaptcha theme to clean
$recaptcha->setOption('theme', 'clean');
//crate captcha object
$captcha = new Zend_Captcha_ReCaptcha();
$captcha->setService($recaptcha);

//finaly create captcha options and create form element
$capOptions = array(
'captcha' => $captcha,
);
$this->captcha = new Zend_Form_Element_Captcha('captcha', $capOptions);


To check if user submited valid capthca use following code:


$recaptcha = new Zend_Service_ReCaptcha(RECAPTCHA_PUBLIC_KEY, RECAPTCHA_PRIVATE_KEY);
$recaptchaResult = $recaptcha->verify(
$this->_request->getParam('recaptcha_challenge_field'),
$this->_request->getParam('recaptcha_response_field')
);
$postData = $this->_request->getPost();
if ($this->form->isValid($postData) && $recaptchaResult)
{
//save your post data
}


Thats it. If you have any questions aks them in comments.

1 comment:

  1. The following error showing, When iam using this code

    Whoops you encountered the below error.

    Missing response field

    ReplyDelete