Building a Secure Contact Form

4.14 (129)

Validating Email Addresses and Spam

It would be quite helpful if we could attempt to validate the email address. What we will do, is validate the email address against a set pattern. By a 'pattern' I mean that we will check if the email address has an @ symbol, as well as a .tld and domain name, etc. This will help stop people entering invalid email addresses format wise, however, this does not check that the email address actually exists.

What we need to do this are regular expressions, or pattern matching functions. We specifically use Perl based regular expressions, however, these are not very different from the PHP standard regular expressions.


This is our email pattern. There are many hundreds of patterns out there, but this is one that I commonly use and works for my purposes. This is going to look very confusing and complicated, I know. But it takes a while to get the hang of it, and requires reading many articles on the topic. I will try to explain it in simple terms.

Ok, the / and the start and end of the pattern are standard and required. The final i indicates that our pattern is case insensitive. Starting from the beginning, the ^ symbol indicates that the pattern must begin at the start of the string, hence, we cannot validate a message (text) with an email address inside it, as valid. The $ symbol at the end, states the same; that the pattern ends at the end of the text.

Next,  ([A-Z0-9\.\-_]+) is a sub-pattern, and says that it can match any number, letter, period, hyphen and underscore character. The plus sign (+) tells us that it must match one or more of these characters. This is not a very accurate pattern as the more experienced would note, as we could validate this email address: .@........jon ; which of course is completely invalid, however, not many people would even attempt to enter that.

Continuing, the at (@) symbol just means we need a total of one @ symbol in our pattern after the previous sub-pattern. We then have another  ([A-Z0-9\.\-_]+) meaning we can have another string of text. Following that,  ([\.]{1}) would indicate that we need to have one period, and then  ([A-Z]{2,6}) shows we need to follow this period with a string of characters only, between 2 and 6 characters long. Now that has been explained; how to use it!

Regular Expression
if (!preg_match('/^([A-Z0-9\.\-_]+)@([A-Z0-9\.\-_]+)?([\.]{1})([A-Z]{2,6})$/i'$emailFrom) || empty($emailFrom)) {
'The email address entered is invalid.';
} elseif (empty(
$emailSubject)) {
'You must enter a valid subject.';
} elseif (empty(
$emailMessage)) {
'You must enter a message to send to our team.';
} elseif ((
$_POST['Reason'] < 1) || ($_POST['Reason'] > 3)) {
'You have selected an invalid department.';
} else {
// The sending code here

We replace our previous set of error checking with this code. Here, to use our pattern, we use the preg_match() function, which takes a pattern and then the text to try and match the pattern to, as parameters. We are checking that the pattern is not matched and also that the email address isn't empty. This allows the user not to enter an email address, incase they want to leave and anonymous message. The rest of the script remains the same.

This is all there is to creating a contact form although in practice we could add more fields, create more beautiful forms and add stronger email validation. It is actually possibly to query the supplied email addresses email server to check if the account actually exists, however, that is out of the scope of this article. Hopefully, you can put this into practice and hopefully reduce spam for yourself.

A Spam Reduction Tip

This doesn't really have much to do with PHP, however since we are on the topic of emailing and contact forms, I thought I'd suggest a method for reducing spam. If you have an email address which users would usually not directly communicate with, e.g. and instead use your contact form, then you can do this nice trick. What you do, is automatically add a random key that you made up (e.g aLKJ3da0) to the subject of the email, and then set your mail blocking rules to only accept mail to this email address with that key somewhere in the subject line. Now, in case someone deletes the key when replying to an email conversation that has been going between you, you should set it so the emails that don't validate to go to another folder to you can periodically check on them.

This method is fairly simple but has proven to remove almost all of my spam. Only if they could implement some method for all emails address to completely eliminate spam.
Rate this article: BAD 1 2 3 4 5   GOOD
<<     Page 3 of 3

Build Your Own Database Driven Website Using PHP & MySQL

  • Installation instructions for Windows, Linux and Mac OS X
  • Instantly apply working code examples from the book to your Website
  • Build a working Content Management System from scratch
  • Master MySQL database administration
  • Fully updated for PHP 5

       Download FREESample Chapters Now!


PHPNerds Newsletter