15
Jan '15

For the benefit of those of you who haven’t heard of them, honeypots are a very cool alternative to captcha codes which protect your forms from spam-bots without requiring any additional interaction or effort from your real users. In a nutshell they exploit the stupidy of spam-bots, by having a special field that would not be filled in by a real user, but which a spam-bot will complete automatically, along with the rest of the form.
The process goes like this:

  • Create an additional field in your form
  • Hide that field from normal users
  • Put a catch in your backend script that checks for a value in this field
  • If the field has a value the script ignores the form submission but still returns the normal ‘thank you for submission’ type message, so the spam-bot assumes it was successful

Firstly to add the hidden field to your form DO NOT use an HTML ‘hidden’ input type as few spam-bots will attempt to give these a value. Instead give the input an innocent sounding class name (I like to use ‘hny’) and throw it off the side of the page using CSS like so:

input.hny {
    position: fixed;
    left: -1000000px;
}

Also make sure the input is named something equally innocent. I often have contact forms with separate first_name and last_name fields and so give my honeypot field the name of ‘name’, but really just pick anything that you’re not already using in your form.

On the server you then simply need to look for a value against this field, and redirect as though the submission was successful. For example (in Laravel):

if(\Input::get('name')) {
    \Session::flash('message', 'Thank you for your submission');
    return \Redirect::route('frontend.index');
}

And you’re done! Easy spam-protection with no extra hassle for your users. Good times!