DIY Honeypot to Stop Spam Registrations

Problem

Here’s a really effective way to prevent registration form spam (and other forms) by using a simple honeypot.

Note: If you’re using Contact Form 7, there is a great plugin for that.

Problem

Our online form is being filled out by a bot, and being submitted. Not only is WordPress filling up with fake users, but in this case, WordPress is linked to a CRM and posted the users over to that system also, causing lots of admin for the team.

Solution

I can’t share the whole code, or even screenshots, but here’s most of it.

At the top of the form, we check:

// Is this spammy?
$spam = false;
$spam_messages = array();

//Check if form has been submitted
if($_POST) {

  // Check the time the form has existed. Less than the threshold means the form is filled too quickly, and probably spam
  $create_time = time();
  if ( isset($_SESSION["reg_form_create_time"]) ) {
    $create_time = $_SESSION["reg_form_create_time"];
  }
  // Calc the time the form was on page
  $form_fill_time = time() - $create_time;

  // Was the form filled in too quickly?
  if ($form_fill_time < 5) {
    $spam = true;
    $spam_messages[] = "Form fill time too short: ".$form_fill_time." seconds";
  }

  // Process the form details
  // Before we save the details, let"s check if they are spammy
  // == Spam Check ==
  // If we have spam, ignore, and redirect to the homepage
  if ($spam) {

    // Email the admin
    $message = implode($spam_messages, PHP_EOL);
    $message .= PHP_EOL . PHP_EOL . print_r($_POST, true);
    wp_mail("[email protected]", "Spam registration", $message);

    wp_redirect( home_url() );
    exit;

  }
  else {
    // Not spam

    // Email the admin
    $message = print_r($_POST, true);
    wp_mail("[email protected]", "Not spam registration", $message);

  }

}

Leave a Comment

Your email address will not be published. Required fields are marked *