An alternative to CAPTCHAs with Symfony2

10 gravatar By Grégoire Marchal - 09/05/2012

Another post about security, an important topic, precisely about how to fight the form spam. I didn't want to impose CAPTCHAs on you on my blog, so I looked for an alternative method to avoid bots. I've quickly found the "honeypot button" principle via this article. Here is the idea: the bots usually submit forms without clicking button, or clicking the first button that looks like a submit button. So we display several buttons, and we verify at server-side that the right button has been used.

Symfonically speaking, we have to create a custom field type to represent the buttons. We also have to add a validation to verify that the right button has been used.

Field type creation

First of all, the buttons need to have a value, so they can be identified during the validation phase. Those values are defined in the parameters.yml file, so they can be easily retrieved via the service container:

# app/config/parameters.yml
parameters:
    # anti spam buttons values
    antispam_button:
        good: xuitybzerpidvfugvo
        bad:  kuserhxvvkigyhsdsf

Then, I create my field type strictly speaking. So I create the AntispamButtonType class. It implements ContainerAwareInterface because we gonna need to use the service container. I define choice as parent of my Type, because this buttons group is used for making a choice, choosing the right button to prove that you aren't a bot. Here is the class:

// src/.../BlogBundle/Form/AntispamButtonType.php

class AntispamButtonType extends AbstractType implements ContainerAwareInterface
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->setContainer($container);
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $antispamParams = $this->container->getParameter('antispam_button');

        $resolver->setDefaults(array(
            'choices'  => array(
                $antispamParams['bad']  => 'do.not.add.comment',
                $antispamParams['good'] => 'add.comment'
            ),
        ));
    }

    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        parent::buildView($view, $form, $options);

        $view->vars['btn_classes'] = array('btn', 'btn btn-primary');
        $view->vars['label_prefix'] = array(null, '<i class="icon-comment icon-white"></i> ');
    }

    public function getParent()
    {
        return 'choice';
    }

    public function getName()
    {
        return 'antispambutton';
    }
}

So I use the service container to retrieve the button values, and I bind them to their label. I've also overridden the buildView method to modify some rendering stuff (CSS classes, button icon).

Let's focus on rendering precisely. Symfony needs to know how this field should be displayed, so let's define a twig template:

{# src/.../BlogBundle/Resources/views/Form/fields.html.twig #}

{% block antispambutton_widget %}
    {% for key, choice in choices %}
        <button name="{{ full_name }}" id="{{ id }}_{{ key }}" value="{{ choice.value }}" type="submit" class="{{ btn_classes[key] }}">
            {{ label_prefix[key] is not null ? label_prefix[key]|raw : '' }}{{ choice.label|trans }}
        </button>
    {% endfor %}
{% endblock %}

{% block antispambutton_label %}{% endblock %}

So I create a antispambutton_widget block ("antispambutton" must match the value returned by AntispamButtonType::getName()) for the field rendering, and an empty antispambutton_label block, to tell that I don't want any label. Now we need to inform the framework that there's a file to parse to render forms. That's in the config.yml file:

# app/config/config.yml
twig:
    form:
        resources:
            - 'MyCompanyBlogBundle:Form:fields.html.twig'

Our field type is now ready to be used! So we can instantiate it in our forms. In my case, it's CommentType, the form to add a comment. But before we need to make this class container aware (as we did for AntispamButtonType), since we gonna need the container to instantiate our field type (and we'll need it for the validation too, see next paragraphs). So the result is:

// src/.../BlogBundle/Form/CommentType.php

class CommentType extends AbstractType implements ContainerAwareInterface
{
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->setContainer($container);
    }

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // other fields...

            ->add('button',  new AntispamButtonType($this->container), array(
                'property_path' => false,
            ))
        ;
    }
}

Don't forget the property_path option, to inform that this field isn't mapped on the Comment object. Now the buttons are well displayed, let's talk about validation now.

Validation

The last thing to do is to verify that the used button value is the expected value. To do so, we just have to add few lines in CommentType::buildForm(). At first, I wanted to use the CallbackValidator class, but it's been deprecated since the 2.1 version. So we have to use the FormEvents::POST_BIND form event (as mentioned in the deprecated comment):

// src/.../BlogBundle/Form/CommentType.php

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $container = $this->container;

    $builder
        // other fields...

        // antispam button + validation
        ->add('button',  new AntispamButtonType($this->container), array(
            'property_path' => false,
        ))
        ->addEventListener(FormEvents::POST_BIND, function(FormEvent $event) use($container) {
            $form = $event->getForm();
            $antispamParams = $container->getParameter('antispam_button');

            if (!$form->has('button') || $form['button']->getData() !== $antispamParams['good']) {
                $form->addError(new FormError('spam.detected'));
            }
        })
    ;
}

Et voila! Now, an error is raised if the right button is not clicked. We just need to translate the spam.detected string in the validators.XX.yml files. So we have an ergonomic and efficient antispam system!


Edit (09/10/2012)

Further to the Jakub Lédl's pertinent comment, I've improved this code. Passing the service container this way is definitely not the right way. The field types aren't supposed to deal with the container. The thing to do is to declare the new type as a service, and to inject the parameters into it.

So let's start with the service declaration:

# src/.../BlogBundle/Resources/config/services.yml
services:
    form.type.antispam_button:
        class: GregoireM\Bundle\BlogBundle\Form\AntispamButtonType
        arguments:
            - %antispam_button%
        tags:
            - { name: form.type, alias: antispambutton }

Then we have to modify the AntispamButtonType class:

class AntispamButtonType extends AbstractType
{
    protected $params;

    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'choices'  => array(
                $this->params['bad']  => 'do.not.add.comment',
                $this->params['good'] => 'add.comment'
            ),
        ));
    }

    // ...
}

Now we can use our field type through its alias: "antispambutton". So here is the CommentType class, freed from its container:

// src/.../BlogBundle/Form/CommentType.php

class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            // other fields...

            // antispam button + validation
            ->add('button', 'antispambutton', array(
                'property_path' => false,
            ))
            ->addEventListener(FormEvents::POST_BIND, function(FormEvent $event) {
                $form = $event->getForm();
                $antispamParams = $form->getConfig()
                    ->getFormFactory()
                    ->getType('antispambutton')
                    ->getParams();

                if (!$form->has('button') || $form['button']->getData() !== $antispamParams['good']) {
                    $form->addError(new FormError('spam.detected'));
                }
            })
        ;
    }

  // ...
}

Note that we have to add the AntispamButtonType::getParams() method, to retrieve the array parameter to use it in the validation callback. I haven't found a better way to do it...

Back home

Comments (10)

gravatar By Matt Robinson, the 09/09/2012 at 2:35 PM
Helpful and interesting thanks. For my contact form, I simply have a checkbox that reads "this is not advertising" and I discard any submissions that don't tick that box. It's weirdly effective!
gravatar By Jakub Lédl, the 09/09/2012 at 5:43 PM
Passing around the service container like that is wrong and entirely unnecessary; instead, use the parameters in your service definitions to instantiate the form types correctly, or better yet, use a container extension to extract the values from your bundle configuration and set the parameters.
gravatar By Tobias Sjösten, the 09/10/2012 at 8:35 AM
This is an excellent approach to combat spam!

I've been testing a lot of different techniques to stop spam without increasing the barrier of entry for my commenters, including a honeypot (http://bit.ly/Q8yxZ1) approach. But the manuals keep getting through…
gravatar By Grégoire Marchal, the 09/10/2012 at 9:48 AM
@Jakub Lédl: Thank you for those hints! I take a look this way to improve my code.
gravatar By PéCé, the 09/11/2012 at 9:43 PM
Hi !
It's a very interesting alternative to Captchas ! But, obviously, the display of an useless button is bit annoying..
From your experience, do bots detect if the button is displayed ?

Thanks for your XP !
gravatar By Grégoire Marchal, the 09/13/2012 at 11:55 AM
Hi,
Actually, yes this button could be hidden with CSS. I think that the most of bots don't detect that.
gravatar By Erik, the 12/28/2012 at 9:31 AM
I like your article. Maybe another approach will work too. What do you think of generating an empty text field hide this field via CSS. The idea is that robots fill this empty field, so when this field is filled it is a bot. If it is not filled it is a human
gravatar By ????, the 04/22/2013 at 3:48 PM
asasasa
gravatar By asdfasdfa, the 05/06/2014 at 11:04 PM
asdfasdfasdfsd
gravatar By Doug, the 07/19/2014 at 10:46 AM
I was loving your idea and was just about to start implementing it as I'm currently having issue's with those pesky kids too but then I read the comments and couldn't help but laugh when I noticed the most recent 2 are spam...

Comment