Robert Basic's blog

Honeypot for Zend Framework

by Robert Basic on April 21st, 2010

I just hacked up a little code snippet based on Matthew's Honeypot Wordpress plugin. It's basically just a Validator for a Zend Form element which is hidden from the user via CSS. Cause it's hidden, users won't see it, but spambots will, well, cause they are bots.

If the element is left empty, it's valid, otherwise it's not.

So, here's the code:

class App_Validate_Honeypot extends Zend_Validate_Abstract
{
    const SPAM = 'spam';

    protected $_messageTemplates = array(
        self::SPAM => "I think you're a spambot. Sorry."
    );

    public function isValid($value, $context=null)
    {
        $value = (string)$value;
        $this->_setValue($value);

        if(is_string($value) and $value == ''){
            return true;
        }

        $this->_error(self::SPAM);
        return false;
    }
}

I add the element to the form like this:

$this->addElement(
            'text',
            'honeypot',
            array(
                'label' => 'Honeypot',
                'required' => false,
                'class' => 'honeypot',
                'decorators' => array('ViewHelper'),
                'validators' => array(
                    array(
                        'validator' => 'Honeypot'
                    )
                )
            )
        );

There. Done.

Happy hackin'!

Tags: framework, honeypot, php, validator, zend.
Categories: Development, Programming.