Posts Tagged ‘Spam Prevention’

Spam-proof Contact Form with PHP/Akismet

Sunday, May 9th, 2010 by Phillip Napieralski

Check out the demo

This is in addition to my previous post about creating a simple contact form. This post will utilize the Akismet service to classify some messages as spam.

The Prerequisites

To follow this tutorial, I assume you already have a simple contact form in place.

Akismet PHP Library

The folks at Aching Brain created a nifty PHP class to make utilizing the Akismet service easier. Download this library then put it in the same directory as your contact form file (Download mirror: AkismetPHPClass).

There are implementations available in other languages as well.


This code will completely replace the PHP code from the previous post. However, I assume the HTML used is unchanged.

First, include the Akismet library:

require "Akismet.class.php";

Now, create a more generic function for sending an email:

function send_mail( $name, $email, $website, $ip, $is_spam, $message)
  		$subject = '';
  		if( $spam == true )
  			$subject = "[SPAM?]"; 
  		$subject .= "[] E-mail received from ".$author_name."//".$author_email."//".$ip;
  		mail( "", $subject, 
		$author_name.", ".$author_email.", ".$author_website. ".\r\n\r\n".$message);

If the $is_spam parameter is set to true, we simply prepend “[SPAM?]” at the beginning of the subject line. This allows us to see right away what it is in our inbox. Further, you could create an e-mail filter to automatically put these messages in a different e-mail folder.

Now, we have to set-up the Akismet class. This will require a WordPress API Key. If you don’t have one, it’s easy and free to get one.

		$wp_key = 'xXxXxXxXxXxX';
		$our_url = '';
		$name = $_POST['name'];
		$email = $_POST['email'];
		$website = $_POST['website'];
		$message = $_POST['message'];
		$ip = $_SERVER['REMOTE_ADDR'];
		$akismet = new Akismet($our_url, $wp_key);
		send_mail( $name, $email, $website, $ip, $akismet->isCommentSpam(), $message);

That’s it! Now if a line of spammers hits your contact form, you have a safe guard against it. If you have questions about this piece of code or anything else, feel free to leave a comment!

In conlusion, Akismet is the best!