DEV Community

Jacek Garbuliński
Jacek Garbuliński

Posted on Edited on Originally published at blixild.com

How to stop contact form spam without a CAPTCHA

A contact form can bring spam submissions every day, like a message offering to spread links across the web for a fee, with every field filled in correctly: a name, an email address and a topic picked from the form's own list. Nobody typed it. A spam bot on a rented server found the form, filled it in and sent it, and someone at the company has to read and delete it. This post shows how to stop contact form spam without a CAPTCHA for your visitors, without cookies and without sending their data to anyone else, and how to tell after a week that it works.

Google's reCAPTCHA, the "I'm not a robot" box or its invisible score, stands in front of every real visitor too, and loads Google's script and cookie with it.

A reCAPTCHA challenge from around 2007: two warped words, "sClt" and "was here", and a box to type them
A reCAPTCHA challenge as it looked around 2007. Image: Wikimedia Commons, public domain.

On our form, a few simple checks do the work. A spam bot that posts straight to the form, without running the page, meets a honeypot field and a timestamp check signed by the server. One that runs the page meets an invisible proof-of-work CAPTCHA, a small puzzle the visitor's browser solves while they type, which took a fifth of a second in Chrome on a laptop. A spam filter for links catches what is left.

The checks in the order the server makes them: a stream of posts narrowing at the honeypot field, the signed timestamp, the proof of work and the link rule, with what each one stops
The checks in the order the server makes them, and what each one stops; not to scale

The post is for small-business website owners getting contact form spam, on WordPress with Contact Form 7, WPForms or Elementor, or on Webflow, and for the developers who look after their sites.

Why bots spam contact forms

The spam submission our form received was an advert: it offered to post links to the buyer's site in bulk across other websites, or to aim the same at a rival's site, sold as "a gift for a competitor". Behind such an offer is a program that fills in forms on other people's sites in bulk. A contact form is one more form to it, and the advert lands in front of a site owner who might buy. Ours came from a server rented from a hosting company.

Blocking that server's address stops only that one; the next post can come from another. The checks below look at the post itself instead. Spam typed by a person passes all of them.

A honeypot field and a timestamp check stop the simplest spam bots

A honeypot field is a form field that people never see and spam bots fill in: off the screen, skipped by the Tab key, labelled "Do not fill this field" for screen readers and not autofilled. A post with anything in it gets the usual thank-you page and nothing reaches the inbox, so the bot's owner sees no difference.

A timestamp check, also called a time-trap, adds the time. When a visitor first clicks into the form, the page fetches the current time from our server, signed with a key only the server holds, and the post carries it back. A spam bot that posts straight to the form's address has no signed time, and a made-up one fails the signature. The post must also come a few seconds later, longer than a bot takes and shorter than the quickest person takes, and each signed time counts once. A time kept only in the page a bot can forge; signed by the server, it cannot be.

Our form had a honeypot field before, and the advert still came through: the bot left the field empty. Neither check stops a bot that loads the page, leaves hidden fields empty and waits.

An invisible proof-of-work CAPTCHA costs visitors a moment and spam bots every message

Proof of work replaces the puzzle a visitor solves with a sum the browser does. Along with the signed time, our server sends a random challenge. The browser tries number after number until one, hashed together with the challenge, gives a result that starts with a set run of zeros. That takes many thousands of tries, and the server checks the answer with one. The visitor sees nothing, no cookie is set, and nothing goes to anyone else.

On a laptop the work took a median of 0.2 seconds in Chrome's engine and 0.05 in Safari's, while the visitor types, and the page keeps responding. With the processor slowed to imitate slower phones, the slowest run took 4 seconds; no real phone was measured.

A spam bot that runs a full browser can do the work, so proof of work does not stop it, but every message costs it time. A browser that cannot do the work still sends the form, and the server asks the visitor to go back and send it again, or to write by email.

reCAPTCHA alternatives and what each costs your visitors

A reCAPTCHA alternative changes what the visitor pays: a puzzle, a cookie, or data sent to another company. The figure sets five common services beside our own checks, as each describes itself on its own pages (read 21 November 2026); the table under it gives the details.

Five reCAPTCHA alternatives and our checks, placed by what the visitor sees and where the visitor's data goes
What the visitor sees and where their data goes, with the price under each name

The details, service by service

Service What the visitor sees Cookies, in its own words Where the visitor's data goes Price How it tells bots from people
reCAPTCHA v2: the "I'm not a robot" box; v3: nothing but a badge sets _GRECAPTCHA when it runs Google free to 10,000 checks a month, then $8 a month to 100,000 a score from 0.0 to 1.0, with 0.5 as Google's suggested cut-off
hCaptcha free plan: an image puzzle; a mode without puzzles on Pro "consent-exempt" cookies and local storage mouse movements, scrolling and key presses, processed in the US free; Pro $99 a month, billed yearly the visitor's behaviour and the puzzle
Cloudflare Turnstile usually nothing; a checkbox if the visitor looks risky a cookie only for its pre-clearance option IP address, connection fingerprint and browser name, to Cloudflare; not the form's entries free, unlimited checks run in the browser, proof of work among them
ALTCHA its widget; the work runs in the background none your own server open-source core free; paid options proof of work, memory-hard if chosen
Friendly Captcha nothing; checks run while the form is filled in none, and no consent needed the IP address, hashed; processed in the EU on its EU endpoint free for non-commercial use to 1,000 requests a month; from €9 a month proof of work and risk signals
Our checks nothing none our own server our own code a honeypot field, a signed time, proof of work

Our checks win on privacy and price: nothing leaves the server, no cookie is set, and nothing is paid. They lose to a spam bot that runs a full browser and waits. Each of the others is the better choice in some case:

  • Turnstile, for bots that run a full browser: its checks look at the browser itself, for free, but every visitor's address and browser details go to Cloudflare.
  • Friendly Captcha, for the same bots on a European business site that would rather pay: it adds checks for automated browsers and proxies, and keeps the data in the EU on its EU endpoint.
  • hCaptcha, when bots get past invisible checks: its image puzzle asks for more than processor time, at the visitor's expense, and the data goes to the United States.
  • reCAPTCHA v3, for a score per visit that your own code acts on: visitors see only the badge, but Google's cookie is set.
  • ALTCHA, for what we built without writing it: proof of work on your own server, with a memory-hard option.

A spam filter for links catches what gets through

A spam bot that gets past the other checks still has to deliver its advert, and adverts look alike. Our form drops a message that puts a link in the name field, carries more than a few links, or pastes the link markup of forums and web pages. A real enquiry rarely does any of these; the advert from the first section did two of them, enough on its own to stop it. The sender sees the usual thank-you page, and the log notes the drop with its reason.

A hosted filter such as Akismet judges the message's text on its own servers, so it can also catch spam typed by a person, which no check in this post stops. For that it receives the text, the sender's IP address and the browser's details.

How to stop contact form spam on WordPress or in your own code

Each setup gets a honeypot field and a time check first, then proof of work or a filter where the tool offers one.

  • Contact Form 7: install CF7 Apps and use its Honeypot app with the submission time check on. For proof of work, the ALTCHA plugin below covers Contact Form 7.
  • WPForms: its honeypot-based anti-spam protection and its minimum time to submit, 2 seconds by default, are on for new forms; check them under Settings » Spam Protection and Security.
  • Elementor: add a Honeypot field to the Form widget.
  • Webflow: under Site settings » Apps & Integrations » Cloudflare Turnstile spam protection, turn on spam filtering and bot blocking, then publish the site.
  • Proof of work on WordPress without code: the ALTCHA plugin runs on your own server with no outside service and covers Contact Form 7 and WPForms. It is installed from GitHub, not the plugin directory, and needs PHP 8.1 or later.
  • Your own code: serve the site over HTTPS, which the browser's hashing needs, and follow the appendix, which has the checks in the order the server makes them; the full version on GitHub adds the rest, with tests.

After a week, count the posts by outcome: dropped by the honeypot, refused for no proof, dropped for a bad proof or by the link rule, and sent. A drop for a proof that was too fast or too old may be a real visitor, so check it against anyone who says a message did not arrive. If spam still reaches the inbox, a service from the table, or a filter such as Akismet, takes the next step.

The form at the end of this post runs every one of these checks.

Appendix: example code

The short version of the checks, to adapt. The full version on GitHub adds time limits, a fallback for older browsers, a store of used challenges for several servers, the honeypot field, the link rule and tests. The values are examples, not ours: tune them for your visitors.

On the server, in Python:

import base64, hashlib, hmac, os, re, secrets, time

KEY = os.environ["FORM_PROOF_KEY"].encode()  # a long random secret in the server's settings, never in the code
BITS, MIN_AGE, MAX_AGE = 17, 4, 6 * 3600     # example values: the work, and the seconds a post may come after
FORMAT = re.compile(r"\A([0-9]{1,12})\.([0-9a-f]{16})\.([A-Za-z0-9_-]{22})\Z")
used = {}                                    # challenge -> expiry; one process only, never emptied here


def sign(head):
    mac = hmac.new(KEY, head.encode(), hashlib.sha256).digest()
    return base64.urlsafe_b64encode(mac).rstrip(b"=")[:22].decode()


def challenge():  # answer GET /form-proof with this as JSON, with Cache-Control: no-store
    head = f"{int(time.time())}.{secrets.token_hex(8)}"
    return {"c": f"{head}.{sign(head)}", "bits": BITS, "min_age": MIN_AGE}


def zero_bits(digest):
    n = 0
    for byte in digest:
        if byte:
            return n + 8 - byte.bit_length()
        n += 8
    return n


def check(c, x):  # "" when the proof holds, else why it does not
    if not c or not x:
        return "missing"  # answer with a message: go back to the form and send it again
    m = FORMAT.match(c) if isinstance(c, str) and isinstance(x, str) else None
    if not m or not re.fullmatch(r"[0-9]{1,20}", x) or not hmac.compare_digest(sign(f"{m[1]}.{m[2]}"), m[3]):
        return "bad"
    age = time.time() - int(m[1])
    if age < MIN_AGE:
        return "fast"
    if age > MAX_AGE:
        return "old"
    if zero_bits(hashlib.sha256(f"{c}:{x}".encode()).digest()) < BITS:
        return "work"
    if c in used:
        return "used"
    used[c] = time.time() + MAX_AGE
    return ""
Enter fullscreen mode Exit fullscreen mode

In the page, for each form marked <form data-form-proof>:

(function () {
  if (!(window.fetch && window.crypto && crypto.subtle)) return; // no proof: the server answers with its message
  var enc = new TextEncoder(), job = null, pending = new WeakSet();

  function zeroBits(buf) {
    var b = new Uint8Array(buf), n = 0, i, v;
    for (i = 0; i < b.length; i++) {
      v = b[i];
      if (!v) { n += 8; continue; }
      while (!(v & 128)) { n++; v <<= 1; }
      return n;
    }
    return n;
  }

  async function solve(c, bits) { // in slices of about 12 ms, so the page keeps responding
    for (var start = 0, t = performance.now(); ; start += 256) {
      var out = await Promise.all(Array.from({ length: 256 }, function (_, i) {
        return crypto.subtle.digest("SHA-256", enc.encode(c + ":" + (start + i)));
      }));
      for (var j = 0; j < 256; j++) if (zeroBits(out[j]) >= bits) return String(start + j);
      if (performance.now() - t > 12) { await new Promise(function (r) { setTimeout(r, 0); }); t = performance.now(); }
    }
  }

  function begin() {
    job = job || fetch("/form-proof", { cache: "no-store" }).then(function (r) { return r.json(); })
      .then(function (d) {
        var at = Date.now();
        return solve(d.c, d.bits).then(function (x) { return { c: d.c, x: x, at: at, min: d.min_age * 1000 }; });
      });
    job.catch(function () { job = null; });
    return job;
  }

  function put(form, name, value) {
    var input = form.querySelector('input[name="' + name + '"]');
    if (!input) { input = document.createElement("input"); input.type = "hidden"; input.name = name; form.appendChild(input); }
    input.value = value;
  }

  function send(form) { form.dataset.proved = "1"; pending.delete(form); form.requestSubmit(); }

  document.addEventListener("focusin", function (e) { if (e.target.closest("form[data-form-proof]")) begin(); });
  document.addEventListener("submit", function (e) {
    var form = e.target;
    if (!form.matches("form[data-form-proof]")) return;
    if (form.dataset.proved) { delete form.dataset.proved; return; } // the second pass, with the proof
    e.preventDefault();
    e.stopImmediatePropagation();
    if (pending.has(form)) return; // a second click while the form waits
    pending.add(form);
    begin().then(function (p) {
      job = null; // each challenge counts once
      setTimeout(function () { put(form, "proof_c", p.c); put(form, "proof_x", p.x); send(form); },
                 Math.max(0, p.min + 200 - (Date.now() - p.at)));
    }, function () { send(form); });
  }, true);
})();
Enter fullscreen mode Exit fullscreen mode

Sources

  1. reCAPTCHA FAQ. Google for Developers. https://developers.google.com/recaptcha/docs/faq
  2. Proof-of-work CAPTCHA. ALTCHA documentation. https://altcha.org/docs/integration/proof-of-work-captcha/
  3. How it works. ALTCHA documentation. https://altcha.org/docs/how-it-works/
  4. reCAPTCHA v3. Google for Developers. https://developers.google.com/recaptcha/docs/v3
  5. Compare features between reCAPTCHA tiers. Google Cloud documentation. https://docs.cloud.google.com/recaptcha/docs/compare-tiers
  6. Cloudflare Turnstile. Cloudflare Docs. https://developers.cloudflare.com/turnstile/
  7. Turnstile plans. Cloudflare Docs. https://developers.cloudflare.com/turnstile/plans/
  8. Turnstile Privacy Addendum. Cloudflare. https://www.cloudflare.com/turnstile-privacy-policy/
  9. hCaptcha pricing. hCaptcha. https://www.hcaptcha.com/pricing
  10. hCaptcha FAQ. hCaptcha documentation. https://docs.hcaptcha.com/faq
  11. hCaptcha Privacy Policy. hCaptcha. https://www.hcaptcha.com/privacy
  12. Friendly Captcha. https://friendlycaptcha.com/
  13. GDPR. Friendly Captcha. https://friendlycaptcha.com/privacy/gdpr/
  14. Use Akismet to filter contact form submissions. Akismet developer documentation. https://akismet.com/developers/detailed-docs/building-your-application/use-akismet-to-filter-contact-form-submissions/
  15. CF7 Apps: Addons for Contact Form 7 (Honeypot). WordPress.org plugin directory. https://wordpress.org/plugins/contact-form-7-honeypot/
  16. How to Prevent Spam in WPForms. WPForms documentation. https://wpforms.com/docs/how-to-prevent-spam-in-wpforms/
  17. Form widget. Elementor Help Center. https://elementor.com/help/form-widget/
  18. Prevent spam in form submissions. Webflow Help Center. https://help.webflow.com/hc/en-us/articles/34277758554771-Prevent-spam-in-form-submissions
  19. Introduction to ALTCHA for WordPress. ALTCHA documentation. https://altcha.org/docs/wordpress/
  20. Get Started with WordPress. ALTCHA documentation. https://altcha.org/docs/wordpress/get-started/
  21. Captchacat.png (a reCAPTCHA challenge, about 2007). Wikimedia Commons, public domain. https://commons.wikimedia.org/wiki/File:Captchacat.png

Top comments (0)