Using Zend to Add ReCaptcha to Contact Form
Over the past few weeks, spammers have been inundating the QuickBase Contact Us form with automated spam. This has been quite a nuisance for the folks at QuickBase who read and respond to these contact form submissions.
In response to the complaints of spam, it was suggested that we add a captcha to the for – so today, I added the captcha using Zend_Captcha_ReCaptcha, a plugin that is included in the Zend Framework. Here’s how it’s done:
Create a reCAPTCHA account & Generate Keys
Create an account here: http://www.google.com/recaptcha
Once there, generate some keys for your domain(s). I created keys for our production domain and my local testing url.
Add the keys to the app config and registry
In your application.ini file, you’ll want to add the keys for production and your staging environment.
----------------------- ReCaptcha ------------------------
recaptcha.pubkey = "YOUR-KEY-HERE"
recaptcha.privkey = "YOUR-KEY-HERE"
[staging : production]
recaptcha.publickey = "YOUR-KEY-HERE"
recaptcha.privatekey = "YOUR-KEY-HERE"
Add Keys to the registry
In your bootloader.php, typically in the _init method, add the keys to the registry.
protected function _initAutoload()
$this->options = $this->getOptions();
Add the Zend_Form_Recaptcha Form Element to your form
In your form class, you need to setup a recaptcha service using Zend_Service_ReCaptcha. It is here that you pass in the registry values for your Recaptcha public and private keys. It is also here that you can specify timeout and the theme to use.
class MyApplication_Forms_ContactUs extends Zend_Form
public function __construct()
//Other Form Stuff Here //
$recaptchaKeys = Zend_Registry::get('config.recaptcha');
$recaptcha = new Zend_Service_ReCaptcha($recaptchaKeys['publickey'], $recaptchaKeys['privatekey'],
NULL, array('theme' => 'clean'));
$captcha = new Zend_Form_Element_Captcha('captcha',
'label' => 'Type the characters you see in the picture below.',
'captcha' => 'ReCaptcha',
'captchaOptions' => array(
'captcha' => 'ReCaptcha',
'service' => $recaptcha
//Other Form Stuff Here - Like a Submit Button, etc) //
Add the form to your controller & view
$this->view->form = new MyApplication_Forms_ContactUs();
if ($this->getRequest()->isPost() && $this->view->form->isValid($this->_getAllParams()))
//Yay - The captcha and all other form rules were validated
Echo captcha in the view:
$this->form->captcha = $form
That’s really about it. Because you’re creating the captcha as an extension of Zend_Form_Element, it will run through the form validator class that Zend provides. This means that errors returned from the captcha service will be handled and decorated just like any other errors with your form.
Enjoy this Post?
Spread the word by promoting this post on FaceBook and Twitter.