Quick and Simple PHP Honey Pot Spam Prevention

This technique has been floating around the web for the past few weeks so it’s definitely worth sharing here. Using standard HTML, CSS and a little PHP, you can filter out a lot of robots and spammers that crawl the web for unsuspecting forms. Credit to Aaron James Young for reminding me about this technique (he posted a similar snippet on Forrst).

A honey pot trap involves creating a form with an extra field that is hidden to human visitors but readable by robots. The robot fills out the invisible field and submits the form, leaving you to simply ignore their spammy submission or blacklist their IP. It’s a very simple concept that can be implemented in a few minutes and it just works – add them to your contact and submission forms to help reduce spam. I’ve used them extensively in my last few projects, I’ve found it to be well worth the small time investment.

Contact Form Example

Here is an example of a simple contact form that uses the honey pot spam prevention method:

View ExampleDownload Source

The HTML:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<form method="post" action="">
    <fieldset>
        <legend>Contact Me</legend>
        <p>
            <label>Name:</label>
            <input name="name" type="text" id="name" />
        </p>
        <p>
            <label>E-mail:</label>
            <input name="email" type="text" id="email" />
        </p>
        <p>
            <label>Message:</label>
            <textarea name="message" id="message"></textarea>
        </p>
        <!-- The following field is for robots only, invisible to humans: -->
        <p class="robotic" id="pot">
            <label>If you're human leave this blank:</label>
            <input name="robotest" type="text" id="robotest" class="robotest" />
        </p>
        <p>
            <input type="submit" value="Send Message" class="submit" />
        </p>
    </fieldset>
</form>

The PHP:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
    if($_POST){
        $to = 'your-email-here@gmail.com';
        $subject = 'Contact Form Submission';
        $from_name = $_POST['name'];
        $from_email = $_POST['email'];
        $message = $_POST['message'];
        $robotest = $_POST['robotest'];
        if($robotest)
            $error = "You are a gutless robot.";
        else{
            if($from_name && $from_email && $message){
                $header = "From: $from_name <$from_email>";
                if(mail($to, $subject, $message, $header))
                    $success = "You are human and your message was sent!";
                else
                    $error = "You are human but there was a problem sending the e-mail.";
            }else
                $error = "All fields are required.";
        }
        if($error)
            echo '<div class="msg error">'.$error.'</div>';
        elseif($success)
            echo '<div class="msg success">'.$success.'</div>';
    }
?>

The CSS:

1
    .robotic { display: none; }

In the above example link, I added some optional CSS to make it look a little nicer. Also, you’ll notice the actual e-mail form doesn’t work, as the to e-mail address is a fake one. The contact form part is just to illustrate the honey pot, the important thing to notice is that the last text field is hidden using CSS (the entire paragraph) and that if text is entered in the field, the entire form fails.

Conclusion

This concept is certainly not my own and in fact, there is even an entire project dedicated to catching spammers using dummy forms and blacklisting their IP addresses (rightfully called Project Honey Pot). Again thanks to Aaron for reminding me about this technique, I’ve been meaning to do a write up on it for a while now. This post is also thanks to Forrst, I’m quite pleasantly surprised at the amount of interesting information I’m finding there.

  • tomsbabyjenna

    I really like this idea, I hate all the spam I see on the internet and anyway to get rid of it would be so nice.

  • Pingback: The Internet Rhetorician : Using a “Honey Pot” to Catch Spam Bots

  • http://montanaflynn.me Montan Flynn

    Simple and sweet! Thanks a bunch.

  • David Crisler

    The only problem is that Google Chrome’s auto-complete feature fills in hidden form fields and totally ruins this technique!

    • http://devgrow.com/ Monjurul Dolon

      Google Chrome shouldn’t be completing a field called “robotest” but if you’d like, you can name it something even more obscure. Most browser auto-complete functions usually just fill out the username and password fields.

      • David Crisler

        I called it all kinds of names, including total jibberish, but Chrome fills it in anyway.

      • Tina Cardigin

        You can name the hidden field anything you want, and Chrome’s autofill will still fill it with data.   You can also try disabling it if you detect the user has Chrome…only that spam bots typically spoof the browser type info as well, so they can theoretically spoof it to be Chrome.

    • Kevin C.

      Add the attribute autocomplete=”off” to the form field

  • http://messtudios muhupwer

    Hi,

    The email form isnt actually working – I get it, but a blank body with nothing written – have tried to fix but no luck..

    Are you sure your php email code is right?

    thanks

    • http://devgrow.com/ Monjurul Dolon

      It should work fine – I’m just using the standard PHP mail() function, which you can read up on here: http://www.php.net/mail

  • http://www.perezfox.com Prescott Perez-Fox

    I recently implemented this tutorial on my site, http://www.perezfox.com, and it works great! Considering I’m a total rookie with PHP, I was relieved to finally be able to understand this one.

    However, I have two questions/things to fix:

    1. When the form is sent, I am redirected to a 404 page. Can I change the redirect to either a “Thank You” page, or perhaps just go no where and stay at the current page. I tried to add a hidden redirect field to the form, but that didn’t work:

    // this didn’t work

    2. Can I expand the error criteria from “blank” to include the default field values? As you can see on my site, I don’t have labels for the input fields, but instead use a default value to indicate what the fields are. (Bad for SEO, perhaps, but I think it makes the form more streamline and mentally forces people to erase the default and fill in their own info)

    Thanks for any input!

  • http://vpg1.com Veeps

    Thanks! I prefer this over Captcha, since I suck at getting them right the first couple o’ tries.

  • http://www.psisalon.waw.pl PsiSalon

    Hi all

    I’ve discovered a site dedicated to grooming.

    Dog grooming refers to both the hygienic care and cleaning of a dog, as well as a process by which a dog’s physical appearance is enhanced for showing or other types of competition. A dog groomer (or simply “groomer”) is a person who earns their living grooming dogs.

    Grooming is an important part of dog care. Depending on the breed, age, and health of the dog, grooming may be a daily activity. Many breeds require significantly less grooming than this, but regular grooming helps to ensure the dog is healthy and comfortable. It is important to note that while many dogs shed, others (such as the Poodle), do not shed (see Moult) as profusely, and require grooming by a professional every 6–8 weeks maximum.

    Dogs can be bathed by being sprayed with a hand-held shower head, or doused with water from a bucket. Often, one bath will not make a dog truly clean. A second bath is excellent to ensure the entire body has been cleaned. Dogs should be bathed with warm, not hot water, in order to make it a more enjoyable experience. Dogs with a heavy or matted coat should never be bathed without first being completely brushed out or clipped of any mats.

    Psi salon

    It’s written in Polish but still have profoundly nice gallery of dogs and cats.
    They use numberless products such as ones of Ring 5, 1 All System, Bio-Groom to look after your pupil.

    Cya all over

  • http://ondietday.com/ Meizitang Botanical Slim

    thanks for you sharing, nice website!

  • http://www.safetrolley.com safetrolley

    wow, this is probably the best anti-spam code i have seen recently. Totally different from the traditional methods!

    thanks man! keep it up!

  • Tim Dawson

    I’ve implemented this (or something very close) for use on a web site form. For the most part it works OK, but some Mac/Safari combinations fill in the honeypot and therefore legitimate enquiries are treated as spam.

    • http://abstrus.de gebeer

      @ Tim Dawson

      are you saying that some Mac/Safari combinations fill the input field or do you mean the field is not hidden in these browsers and humans filled them?
      And what text do these browsers fill in?

  • Cesar

    Great article, and what a great solution to this annoying problem, I’ve used captcha in the past, but I’m definitely switching to this solution from now on.

    Thanks!

  • Pingback: Honey Pot results not working. I need a PHP nudge in the right direction. - Tech Forum Network

  • Bruce

    OK, a novice here, and I have looked around for an answer before posting this. But if I want to add other fields to the form in order to receive additional information, where do I add those field names in the php to get the to show in the email? I have added them to my form already but can’t seem to get them to show in the resulting mail.

    Like I have a form fields “something”, “something2″, “something3″. Any help would be greatly appreciated.

    • Bruce

      Figured it out! no replies needed.

  • Alan Smith

    Hi. I am a php novice. How can I parse the php into html? I want the file extension to be .html instead of .php

    • Sasi

      use htaccess rewrite rule

  • Alan Smith

    This is how my file looks when I change the extension from .php to .html
    http://www.francorpme.com/honeypot.html 

  • Luacevedo

    Brilliant, thank you so much
     

  • David

    we experinece a lot of Spam so have implemented this on our php form with an existing form will this work? please see code below..

    <?php
    $to = 'removed';
    $from = $_POST['contact_email'] ;
    $name = $_POST['contact_firstname'] . $_POST['contact_surname'] ;
    $robotest = $_POST['robotest'];
    $headers = "From: $from";
    $subject = "Website Enquiry";

    $fields = array();
    $fields{"contact_firstname"} = "contact_firstname";
    $fields{"contact_phone"} = "contact_phone";
    $fields{"contact_email"} = "contact_email";
    $fields{"contact_message"} = "contact_message";

    if($robotest)
    $error = "You are a gutless robot.";
    else{
    if($name && $from && $message){
    $header = "From: $name “;
    if(mail($to, $subject, $message, $header))
    $success = “You are human and your message was sent!”;
    else
    $error = “You are human but there was a problem sending the e-mail.”;
    }else
    $error = “All fields are required.”;
    }
    if($error)
    echo ”.$error.”;
    elseif($success)
    echo ”.$success.”;
    }

    $email2 = stripslashes($_POST["imahuman"]);
    if (!empty($imahuman)) {
    header(“location: pretend_that_email_sent.php”);
    exit();
    }

    $body = “We have received the following information:nn”; foreach($fields as $a => $b){ $body .= sprintf(“%20s: %sn”,$b,$_POST[$a]); }

    $headers2 = “From: removed”;
    $subject2 = “Thank you”;
    $autoreply = “To confirm your enquiry has been received. Someone will get back to you as soon as possible, usually the same day but in any event within 24 hours.

    Thank you”;

    if($from == ”) {print “You have not entered an email, please go back and try again”;}
    else {
    if($name == ”) {print “You have not entered a name, please go back and try again”;}
    else {
    $submit3 = mail($to, $subject, $body, $headers, “-fremoved”);
    $submit4 = mail($from, $subject2, $autoreply, $headers2, “-fremoved”);

    if($submit3)
    {header( “Location: http://www.removed” );}
    else
    {print “(We have encountered an error sending your mail, please notify removed”; }
    }
    }
    ?>

  • Pingback: Zac's Attic Blog » Fight Spam – Using Nothing!

  • Steve

    Just wondering. Does anyone have thoughts about whether hiding via CSS declaration vs. hiding programmatically via javascript would work better, i.e. thwart the bots more effectively? I realize that a few legitimate visitors might have javascript turned off but that’s not even a concern of mine since most of the Web these days is not useable if js is turned off. Also, can/do bots have javascript enabled? If so, that might answer my question.

  • jeff

    I changed the email address to my own and uploaded it to my server. i send myself an email and it says that i am human and that the email was sent. but i never receive the email. i have another contact form and all i did for that one was to enter my email address as well. i know very little about php. can someone help me figure out what I am doing wrong?

  • Pingback: email form being hacked? - DesignersTalk

  • novice

    Great work, and so easy. I’ve never managed to use php before, but your model was so easy. And works perfectly.

    Here are just a couple of useful clarifications for novices like me; I worked them out with a bit of help.

    The PHP text goes into a separate file which you can call what you want, let’s say hello.php

    Make this using a simple text editor like notepad. Save the file as hello.php (or whatever)

    The html goes into your contact form html document..

    In the first line of code, put the name of your php file into to the ” ” following action, to give

    Put your css in the header. If you don’t know how to use css, then the fourth field will show, but the form still works fine

  • Pingback: 20+ Free CAPTCHA Scripts and Anti-Spam Solutions & Services | NetWaver

  • test

    test

  • Pingback: Honeypot validation - Tech Forum Network