Save Your Contact Form from Bots!

Table of Contents

This time I’m going to help all developers protect their contact forms from spam bots.
These bots abuse forms by sending spam messages or junk data. Fortunately, there are simple ways to slow them down.

The Anti-Spam Question

One easy approach is to add a simple anti-spam question — something a human can answer but a bot cannot.

Here’s a basic example in PHP:

<?php
// To mitigate the possibility of user errors, eliminate case-matching issues
$posted_var = strtolower($posted_var);
$answer = strtolower($answer);

// If $posted_var doesn’t match $answer
if ($posted_var != $answer) {
    // Return an error or set a feedback/output variable
}
?>

Regulating Input Lengths

Another simple technique: limit how many characters users can enter in each input field. This prevents bots from flooding your form with massive data.

Example:

<?php
// If the $posted_var is greater than sixty characters…
if (strlen($posted_var) > 60) {
    // Return an error or set a feedback/output variable
}
?>

These are two of the methods I usually use — simple but effective ways to protect your forms.