Skip to content
OSULZER.AT
Security12 min read· updated March 3, 2022

Fighting Spambots Without a Captcha

Keep spambots out of your contact form without an annoying captcha. A honeypot field and a timestamp check in PHP, HTML and CSS stop most bots.

This post is from 2019 - some of its content may be outdated by now.

Contact forms are a good way to give visitors to your website or blog the chance to get in touch. But bots have always been interested in sending unwanted advertising through these channels as well. The big advantage of contact forms for spammers is that the email resulting from the form is very likely to actually be read. There are now various approaches to keep bots from filling out forms on your website. One of the better-known solutions is, for example, a security question or Google’s reCaptcha, which shows the user picture puzzles from time to time that have to be solved. Neither solution is ideal for real website visitors, and both can quickly become a nuisance. In the case of reCaptcha, data protection also plays a role. From a technical point of view, the data Google collects from the form is limited to the captcha, but using it is still not entirely free of concerns. You should assume that Google records user data such as the IP address, user behavior, and browser details. Without an appropriate privacy notice, using it can become problematic. Apart from captchas and security questions, though, there are other ways to successfully keep bots out.

What Do Spambots Actually Do?

Before we look at the approaches, here is some interesting background on how most bots work. Bots are basically scripts that automatically crawl the internet for websites and then search them specifically for forms, email addresses, and other information. The spambot jumps from page to page by following the links on each page. The Google spider does essentially the same thing: it visits a page, analyzes the content, sends information to the Google servers, and then jumps from page to page. The big difference between bots such as Google’s and spammers’ bots is their behavior around forms. Google bots do not fill out forms, while spambots love forms.

Advantages of Spambots

Spambots are built for speed and at the same time try to use as few resources as possible. For spammers, quantity beats quality and time is money. Running a spam server costs money, and in most cases the spam messages that are sent have only a small chance of success. The goal is therefore to send as many spam messages as possible. Many bot instances run on each server at the same time, all crawling the internet simultaneously. To be able to run more bots per server, bots use simple requests that are sent to web servers. The returned HTML code is then analyzed. Included CSS or JavaScript code is usually not interpreted, in order to save resources and time.

Approaches to Fighting Spambots

So we have a rough idea of how spambots work and what goals they pursue. A bot that lands on your website crawls all the subpages, stops at every form it finds, and tries to fill it out and submit it. We can assume that the majority of bots ignore things like CSS and JavaScript. This circumstance, which can also be seen as an advantage of spambots, can be turned to our advantage.

Honeypots

A honeypot is an area of your website that is hidden or made unrecognizable to normal visitors. In our case, we will build a honeypot into our form in the form of an input field. The field is then hidden using CSS or, if you prefer, JavaScript. Spambots that visit our page and find the contact form see the honeypot as a normal input field and are tempted to fill it out. When processing the form, a short check of whether the honeypot input field was filled out is enough to assume with reasonable certainty that the request was sent by a robot.

Timestamps

A normal visitor needs a certain minimum and maximum amount of time to fill out a contact form or comment form. You can safely assume that at least 10 seconds pass between visiting the page and submitting the form. Bots can do this work in a few seconds. So we only need to find out how much time passed between the page load and the form submission to identify possible bots.

With these changes, bots that visit our page and want to submit forms first have to get past the honeypot field and then submit the filled-out form at the right time.

Implementation with PHP, HTML, and CSS

Let’s first take a look at our HTML form, with suitable background information on the individual fields.

    <form action="contact.php" method="POST">
      <!-- # Fields to be filled out by the user -->
      <div class="formfield">
        <label for="name">Name:</label>
        <input type="text" name="name">
      </div>
      <div class="formfield">
        <label for="email">E-Mail:</label>
        <input type="email" name="email">
      </div>
      <div class="formfield">
        <label for="message">Ihre Nachricht</label>
        <textarea name="message"></textarea>
      </div>


      <!-- Security fields
        A previously generated "fingerprint" is stored in the nonce field,
        which is checked later in the actions controller. The nonce, also called CSRF
        token, is needed to make cross-site attacks harder.
        CMS systems such as WordPress or frameworks such as Laravel have suitable functions
        for including these fields and for verifying them. In this example, the field
        only serves to point out that you should definitely use these functions.
      -->
        <input type="hidden" name="nonce" value="publicsecret1">


      <!-- Honeypot field
        Spam bots look for known names in form fields to be able to tell individual
        fields apart. Almost every bot can distinguish between
        the different kinds of text fields. If a text field is marked as hidden,
        bots ignore it. For this reason, our honeypot field
        gets the value "display:none;" via CSS. This prevents the browser from
        showing the field to the visitor, while simple bots assume that the field is visible. In addition,
        the field gets the tempting name "subject". If our "subject" field is filled out
        during the later check, we can block the request right away.

        Addendum: More sophisticated bots can detect elements hidden via CSS and
        will not fall into the trap.
      -->
      <input type="text" class="noeyes" name="subject" value="">


      <!-- Timer field
        For spammers, time is money. A bot therefore does not stay on a page for long
        before jumping to the next one. The required information
        is retrieved, and if a contact form or another target
        is on a page, it gets attacked.
        The time a bot needs to fill out a form is often under one second.
        We can use this to our advantage. In the timer field, we place
        an encoded timestamp that is generated when the page is requested.
        During validation of the form, we check the timer to see how quickly the
        form was filled out and submitted. Forms that were filled out
        and submitted in less than 5 seconds can then be blocked with reasonable certainty.

      -->
      <input type="text" class="noeyes" name="phone" value="<?php echo generateTimeHash($key, $cipher, $iv); ?>">

      <input type="submit" value="Absenden">

    </form>

In the example, we first have our normal input fields for name, email, and the message to be sent. After that, for demo purposes, I added a so-called nonce field. The “nonce” is meant to ward off cross-site request forgery attacks and should be used in every form on your site. Practically all CMS systems and frameworks offer this function, and you should definitely use it. In the demo, the fields are present but not equipped with any functionality.

The form field gets interesting with the next input field, named “subject”. This field is our honeypot field. The name of the form field is chosen so that possible bots register it as a subject field and fill it out accordingly. The form field is hidden via CSS and is therefore not visible to normal visitors. We hide the field via CSS because bots would ignore form fields of type “hidden”.

After our honeypot field comes our timer. In the timer field, we place an encrypted timestamp that is generated and inserted via PHP when the page is created. We also hide this field via CSS and give it a name that is interesting to bots, to provoke changes to the field. In our contact.php file, which processes requests, this field is then decrypted and checked. Of course, while we are at it, we also check whether a bot has made changes to the field.

Below is the function responsible for creating the encrypted timestamp.

// the key we use to encrypt our timer field
$key = 'MySecretHashkey876574';

// second unique key for encrypting and decrypting the timehash
$iv = '0259847523614897';

// the encryption method
$cipher = 'aes-128-cbc';


// creates encrypted timestamp field
function generateTimeHash($key, $cipher, $iv) {

  // create current timestamp
  $time = new DateTime();

  // check whether the encryption method is available, or die
  if(in_array($cipher, openssl_get_cipher_methods())) {

    // returns encrypted timestamp value
    return openssl_encrypt($time->getTimestamp(), $cipher, $key, 0, $iv);

  }

  die('Verschlüsselungsmethode nicht gefunden oder Fehler bei Verschlüsselung');

}

To encrypt the timestamp field, we use the PHP function openssl_encrypt. We pass it the current timestamp, the encryption method, a key, and an initialization vector. The function also tests whether the chosen encryption method is available and ends the script if it is not. In the finished form, the timestamp field then looks like this.

Let’s move on to contact.php, where we process the request we receive. We start with our honeypot field. As described above, this field must be empty. If it is filled out, the request most likely comes from a bot. We test whether the POST variable exists and whether it is an empty string, as expected. In the demo, we end execution if the subject field was not submitted.

$honeypot = isset($_POST['subject']) ? $_POST['subject'] : die('Betreff Feld gelöscht');


/*
  If the honeypot field is not empty, we assume that a bot
  has fallen into our trap.
*/
if(!empty($honeypot)) {
  $failmessage = true;
}

In the next step, we take care of our timestamp variable. It must be submitted to us and it must be possible to decrypt it successfully. If decryption does not work, the input field was edited. This means that the bot or the user on the other end has unwanted intentions, so the request is blocked. If the timestamp field can be decrypted, we compare the current time with the submitted time and determine the elapsed seconds against our minimum and maximum values.

/* Minimum time in seconds that must pass after the page was delivered
  so that the request does not end up in the bot filter
*/
$minTime = 5;

/* Maximum time in seconds that may pass while the form is being filled out.
  Some bots fill out the form and submit it at a later point to get around this
  kind of security check.
*/
$maxTime = 3600;

$givenTime = isset($_POST['phone']) ? $_POST['phone'] : die('Timestamp Feld gelöscht');

// decode submitted timestamp
$decryptedTime = openssl_decrypt($givenTime, $cipher, $key, 0, $iv);

// check whether the submitted value could be verified
if($decryptedTime) {

  // create current timestamp
  $currentTime = new DateTime();
  $currentTime = $currentTime->getTimestamp();

  /*
    Now we calculate the seconds the user
    needed to fill out the form. If the value is below our threshold, we block
    the request.
  */
  if( ($currentTime - $decryptedTime) <= $minTime || ($currentTime - $decryptedTime) >= $maxTime ) {
    $failmessage = true;
    $timeError = 'Minimale Zeit für Ausfüllung unterschritten / überschritten';
  }

} else {
  // the supplied value could not be decrypted -> input field was edited
  $failmessage = true;
  $timeError = 'Verschlüsselter Zeit-String wurde bearbeitet';
}

If the $failmessage variable is true after execution, the chances are good that the request came from a bot. The variable $honeypot contains the text that was entered into our honeypot field, or is empty if the field was not filled out. The variable $timeError is set if there was a problem decrypting the submitted data, or if the elapsed time fell below or exceeded the thresholds. Finally, here is the output of contact.php in our demo.

<?php
/*
  In this demo, the POST variables are not filtered or validated!
*/
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

?>


<html>
  <head></head>
  <body>
    <p>
      <?php if( $failmessage ) {
        echo '<span style="color:red;font-weight:bold;">Bot Aktivität entdeckt</span>';
      } else {
        echo '<span style="color:green;font-weight:bold;">Keine Bot Aktivität entdeckt</span>';
      }
      ?>
    </p>
    <p>
      Ihr Name: <?php echo $_POST['name']; ?><br>
      Ihre E-Mail: <?php echo $_POST['email'];?><br>
      Ihre Nachricht: <?php echo $_POST['message']; ?>
    </p>
    <p>
    Honeypot: 
    <?php 
    if(!empty($honeypot)) {
      echo '<span style="color:red;font-weight:bold;">ausgefüllt</span><br> ';
      echo 'Eingegebener Text: ' . $honeypot;
    } else {
      echo '<span style="color:green;font-weight:bold;">nicht ausgefüllt</span>';
    } ?>
    <p>
    <p>
      Zeitfeld:
      <?php if( !$timeError ) {
        echo '<span style="color:green;font-weight:bold;">Vergange Zeit in Sekunden:' . ($currentTime - $decryptedTime) . '</span>';
      } else {
        echo '<span style="color:red;font-weight:bold;">' . $timeError . '</span>';
      }?>
    </p>
  </body>
</html>

I have made all the data from the demo created for this post available to you in this .zip file. Download

Conclusion

Simple bots can be locked out quickly with these first measures. One advantage of these measures is that real visitors do not notice them at all. What our demo lacks is further logic that locks out potential attackers after several attempts. A time-based block or a blacklist is conceivable. Unfortunately, the legal viability of a blacklist under the GDPR is questionable. It is also possible to pretend to the bot that its request was successful while not performing any actions in the background. Another option would be to show the bot a 404 error page and make it believe that the form leads nowhere.

Smarter bots that, for example, submit forms with a delay and can also read CSS or JavaScript will unfortunately be little impressed by the measures shown above. Possible additional safeguards would be, for example, a one-time token that is stored in each visitor’s session and checked when the form is processed. If all else fails, you can of course still add a security question as a last resort.

If you have further tips for fighting form spam on your own website, feel free to leave them in the comments.

I am also happy to help with implementing solutions against spam. Contact me, or learn more about my other offerings in website development.

WordPress Maintenance

So it never comes to that

Tested updates, daily backups, and malware protection - from €40 per month.

See maintenance

New project?

Contact.

Tell me briefly about your project - I'll get back to you personally.

Your data is used solely to handle your inquiry. More in the privacy policy.