How to Build a Spam-Filtering PHP Contact Form that Doesn't Suck
This site has one purpose: to teach you how to incorporate some spam-filtering into a PHP contact form to reduce the success rate of robotic spam submissions without having to use CAPTCHA images, pictures of cats, or other human-authentication methods that annoy users. It's not designed to be a comprehensive spam solution nor to scan for viruses, ransomware, or scams. It's designed to reduce the amount of spam (especially robotic spam) accepted through the contact form, and nothing more.
I've been using forms based on the principles I'll share on this site for more than 15 years, with a false-negative rate of less than five percent and an extremely low false-positive rate.
This site assumes the following:
- A Web server that supports PHP > 7.0.
- The scripts used as examples on this site also assume that the mail() function of PHP is enabled. This is almost always true, but it is possible for a Web host to disable it; so if your script doesn't work, that may be the reason.
- Enough knowledge of HTML to be able to build a basic form.
- Entry-level knowledge of PHP.
I emphasize entry-level because the scripts I'm going to use as examples are not necessarily the most elegant or efficient ways to do what they do. They're merely the easiest ways I could think of for someone who's not a PHP guru to understand them and modify them for their own use.
These scripts, as presented here, use PHP's built-in mail() function. They can also be used with other mail systems and servers, but I'm not going to discuss them here. This site is more about filtering mail sending mail. (I will mention, however, that if you choose to use a mail system that requires authentication, you'll have to create a user and password for the script's mail sender.)
The Basic Contact Form
For purposes of illustration, I'm going to begin with a basic contact form:
<!DOCTYPE html> <html> <head> <title>Test Form Page</title> </head> <body> <form method="post" action="path-to-form-processor.php"> <p> <input name="name" required> <label>Name</label> </p> <p> <input name="email" type="email" required> <label>Email</label> </p> <p> <input name="phone" required> <label>Phone</label> </p> <p> <select name="subject"> <option label="Compliment" value="Compliment">Compliment</option> <option label="Complaint" value="Complaint">Complaint</option> <option label="Poem" value="Poem">Poem</option> <option label="Song" value="Song">Song</option> </select> <label>Subject</label> </p> <p> <textarea name="message" required></textarea> <label>Message</label> </p> <input id="submit" name="submit" type="submit" value="Submit"> </form> </body> </html>
The form will collect the following inputs and pass them on to the form processor:
The following pages will explain how to take that input and analyze it for characteristics of robotically-generated spam. Let's start by learning how to build a spam-filtering contact form page.