How To Prevent Spam in PHP Forms

By Carson on October 25, 2009

Matrix Coding

I decided to include a quick contact form in the footer of my new web page design (seen here). I taught myself the basics of PHP to get the form working and all was well.

A few days ago I started getting a lot of spam through this quick contact form. I searched the web high and low all day to find a way to stop these annoying spam bots. Finally I came across a simple solution that has worked wonders so far.

Spam bots are not smart, and will try to fill out every available input area in order to fulfill any potential required fields. How can we use this to our advantage? We will use what is commonly referred to as a honeypot.

A honeypot is an invisible field that lures spam bots to enter text into it, but we want it to be empty.

  1. Add the invisible input area with the following code:<input style="display:none; visibility:hidden;" name="validation" type="text" />
  2. Define honeypot in your .php file as:$honeypot = $_POST['validation'] ;
  3. Then insert the following:if (!empty($honeypot)) {
    header( "Location: http://www.domain.com/your-error-page.html" );
    }
  4. Most likely, you will change that if to elseif and put it inside your main function.

That’s it. Now your form should work just like normal, except it will go to your error page and not submit if that hidden field has text in it. Remove the style from the input tag and test it for yourself.

Thanks to Doug Hockinson for having a site with such great resources.

Spread the Words:
  • Twitter
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Sphinn
  • Technorati
  • E-mail this story to a friend!
Carson
About the Author:

Carson Shold is a freelance graphic and web designer born in Victoria, BC and living in London, Ontario. He is a ‘for hire‘ designer that wants to help your business stand out – the right way. You can connect with him and his thoughts on twitter or check out his portfolio at carsonshold.com.

Leave a Reply

Coke To Send Bloggers Worldwide
Top 25 Inspiring Square Logos