Blog

Back 4 Comments

SPAM Protection Using PHP and jQuery


The most common solution to keep 'machines/automated spammers' from abusing PHP forms is to use a CAPTCHA. This works, for the most part, but is very inconvenient & usually unsightly for the visitor, discouraging them from actually using the form for its intended purpose.

The solution we've come up with is much simpler than other proposed solutions we've run across.  We hope you find it helpful.

Here's how it works: (view demo · source · download)

  • Give your required form field a specific class
  • After a visitor enters information in the text field, a call is made to the PHP script, using jQuery
  • The PHP script sets a session, confirming that the visitor is actually a real person since they must have clicked on one of the form fields.
  • Since the session is set, the visitor is allowed to send the form.

 


The only downside we can think of is that the form won't work unless the visitor has Javascript enabled, but typically over 95% of visitors to your site will have Javascript enabled.

 
UPDATE:  (4/10) - Looks like someone else had a similar idea first:  http://15daysofjquery.com/examples/contact-forms

Andy H
April 9, 2009 9:00am
Interesting idea. You may want to check http://developer.yahoo.com/security/#xsrf -- specifically their section on that page starting with "If your development framework supports a user session container (e.g., PHP), then generate a unique signature with a timestamp and store it in the session with each request, and embed it in your forms/URLs so that it is passed back to the server with subsequent requests."
John
April 9, 2009 12:59pm
Thanks, Andy. I've made some changes to the code based on your suggestion.
Rostislav Stoyanov
July 1, 2009 5:41pm
it will not work if you have same form in several tabs. if you submit on first, other tabs generate error after sending. try it
ฟดก
September 14, 2011 3:26am
หดกหดฟห


Your comment has been posted....