Web Development

Simple PHP+CSS+jQuery Anti-Spam Measure

Today I set out to implement some additional anti-spam measures for some forms on one of my sites. Let me start by saying that this should not be the only thing you do to prevent spam. Nor are these ideas new or unique. This is just a simple technique to help prevent spam.

Step 1 – Add a New Form Field to the HTML Form

I like to use a simple checkbox like this:

<label class="required_field">
<input type="checkbox" required id="required_field" value="1"> You must check this box

Please note that the input has the attribute of “required“.  This means that the field is not optional, and must be filled out in order to submit the form.

Step 2 – Remove the New Form Field using CSS

Add some basic CSS to hide the checkbox from the human visitor like this:

.required_field {

Step 3 – Remove the Attribute “required” using jQuery

This doesn’t have to be done with jQuery, and you can adjust this for your favorite javascript library, or handmade solution.


Step 4 – Use PHP to Determine if the New Form Field is Checked After Submission

if (isset($_REQUEST['required'])) {
// Check for bots
$spambot = $_REQUEST['required'] ;
if ($spambot) {
// Give spam bots the shaft
}  else {
// Carry on, do whatever it is you do with your form

In Review

We have added a required form field using HTML, and hidden it from view from the visitor. At this point, the visitor cannot submit the form due to the required field not being filled. So we remove the required attribute using jQuery/javascript. Once that happens, the form can be filled out and submitted by a real visitor. Submissions by Spam Bots that filled out the bogus hidden required field get the shaft.

What’s wrong with this technique?

It requires that javascript be enabled. Visitors without javascript will also get the shaft. You should weigh the cost of that based on your own analytics.

By Tim Bunch

Tim Bunch is a Web Developer from Rockaway Beach, Oregon. As a web standards fanatic, he passionately pursues best practices. He also actively engages people on a wide range of topics in a variety of social media networks. Tim is also an avid Wordpress developer, music maker, coffee drinker, and child raiser. @timbunch

Leave a Reply