Web Development

Use PHP STRISTR To Stop Comment Form Spammers

It’s not often that spam gets past my defenses. However, when it does, it’s really annoying. So today I set out to stop comment form spammers from submitting forms with one or more links.

PHP’s STRISTR searches a string for anything that matches your search. So, searching for “http://” will return true if it is found in the string. This will only work on form fields that you do not want to allow a link to be added. So, it may help to give visitors a heads up before they post a comment with a hyperlink included.

Check A Single Variable For Links

if (isset($_REQUEST['message'])) {
$message = $_REQUEST['message'] ;
if(stristr($message, 'http://')) {
  // Send visitor to your honeypot, an error page, or kill the script with die();
$message = stripslashes($message);

I include the above code in my PHP script that processes my form. Of course, you will have to replace the variable $message with your own variables. I also use this on name fields to prevent bots from placing links there.

Check All Variables For Links

So what if you want to automatically scrub all of your variables right off the bat? I have a solution for that too!

foreach($_REQUEST as $key=>$value) {
  if (!isset($all_variables)) {
    $all_variables = $value;
  } else {
    $all_variables = $value.$all_variables;
if(stristr($all_variables, 'http://')) {
		die('No Links Allowed');

You could then perform other checks on the same string. For example, common spammy words.

You may also want to use this simple anti-spam technique.

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