PHP & HTML – easy spam prevention using hidden form fields (sample code)

The easy and fast working method of securing your forms agains spam bots is as easy as a few lines of PHP and HTML code.

Spam bots, at least, most of them, crawl random websites and fill their forms with all kind of ads or unwanted content. There are a lot of alternatives to stop this, Google Captcha, reCaptcha, etc., I used all of this methods, they work pretty well but, sometimes, when you move your site to a new server or domain, you need to spend a lot of time working around this methods to make them work again.

I simply tried a really simple method that I found a few years ago, the method implies using simple PHP and HTML to trick the bot to fill a field that the user doesn’t see(hidden via CSS).

The code is pretty simple…

Here is the HTML…

<form action="sample.php">

<input type="text" name="name" placeholder="Nume" required="">
<input type="text" name="email" placeholder="Email" required="">
<input type="text" name="phone" placeholder="Telefon" required="">

<input type="text" name="city" class="vho" id="send" placeholder="Paris">

<button type="submit">Submit</button>
</form>

<style>
.vho { display: none }
</style>

 

Here is the PHP…

<?php

if(isset($_POST['city']) && !empty($_POST['city'])) {

echo "Hello SPAM Robot!";

exit;

}

if(empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone'])) {

echo "Hello SPAM Robot 2!";

exit;

}

?>