Nico Petri
Nico Petri's Blog

Nico Petri's Blog

Arming Your Forms Against Spambots

Arming Your Forms Against Spambots

A Different And Lightweight Approach

Nico Petri's photo
Nico Petri
·Jan 11, 2022·

2 min read

If you find yourself in a situation where you cannot or simply don't like to use a captcha, then this method might be helpful for you.

The spam hell

Getting a lot of spam is always painful. It floods your inbox and the risk of deleting or missing an important email is getting higher and higher along with the amount of spam emails you receive. So the prevention of getting too much or any spam email can save you time. In the best case, spambots only sends you advertising. But they will also deploy their scam messages and exploits etc. So these bots were also a possible security risk for yourself or your clients. But how spambots are working and how can we handle them.

Usually a spambot crawl your website for forms, enter some random but valid data in all input fields and add their spam content in the message's textarea (technical, they just compose their own requests). Then they use the submit event/action and the data is being sent. All this happens in less than a second.

I show here a simple way how to catch a lot of spambots.

The Action Swap

  1. Preset the form action with a fake action. This can be a route or URL that actually exist and produces no 404 HTTP error. You might also make use of a complete random URL. That's up to your taste.

  2. Set the real action by JavaScript with a timeout of a few seconds.

Let's assume we have this simple form.

<form action="/" id="myForm">
  <input type="text" name="input" placeholder="Imput some text">
  <button type="submit">Send</button>
</form>

Then you can use this simple script to replace the action after five seconds.

  <script>
    setTimeout(() => {
      const el = document.querySelector("#myForm")
      el.action = "/send-form.php"  
    }, 5000)
  </script>

And that's it. A human user will be not be affected by this delay, because it takes some time to fill the form, and at this point the working action is already set. You might show a counter and/or disable the button until the action is set, just to let the user know. That's up to your taste.

So this is a super easy and lightweight approach and need only few lines of code. At a client's site where I use this Action Swap, it traps more than 95% of all bots.

 
Share this