» WordPress Coding & Design » Create a Contact Page Part II

SarahCreate a Contact Page Part II

Written by Sarah from Stuff By Sarah on August 31, 2008

Last week I started a short series on creating a contact page for your site, and wrote about the form markup and CSS. This week I’m writing about validation. Contact forms are notorious for being insecure and left wide open for email header injections, allowing someone to hijack your form and spam anyone and everyone through it. However, there are steps you can take to ensure the email address supplied is valid, even the name given, is of a valid format (ie. a name!).

Validate the Email Address

There are 3 functions we can use to validate the email address. These functions were originally written by Khalid Hanif and there is also more info on his blog post concerning these. The functions are

// check no additional lines have been added to the email field
function has_newlines($text) {
	return preg_match("/(%0A|%0D|\n+|\r+)/i", $text);
}

// Check that additional headers haven't been added
function has_emailheaders($text) {
	return preg_match("/(%0A|%0D|\n+|\r+)(content-type:|to:|cc:|bcc:)/i", $text);
}

// check the email is of a valid form
function is_valid($text) {
 	return preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix",$text);
}

(Note, I’ve amended the last function to modernise it and have it allow longer TLDs on the email).

The first function checks whether additional lines have been added. If you check my example of email header injections then you’ll see how multiple lines were added. The second function checks for the appearance of to, cc or bcc. Again, these are needed for header injection. The final then validates the email and checks that it is of the required format @domain.[tld or country domain] which would allow username@test.com and user.name@test.co.uk through. It allows up to 6 characters as the TLD which would then cover the .museum TLD.

To use these functions to check the given email you could use the following statement. At this point I’m going to start using a variable called ‘formerror’, which is false when all the validation checks pass, and becomes true when an error is found.

if (has_newlines($email) || has_emailheaders($email) || !is_valid($email)) :
    $formerror = TRUE;
endif;

Validate the Name

You may wonder why bother validating the name. This is more to ensure you do not get spammed. Anyone used to receiving form spam will know that a lot of spambots are simply programmed to put the same URL in every box on the form. So if you validate the name field then you’re potentially reducing the amount of spam you may receive from the form.

To do this we want to check that the name contains characters of A-Z, hyphens, fullstop (period), single quotes and of course spaces. We also want to allow foreign characters that the standard A-Z do not include. To do this we need to use a regular expression and see if the name given matches the expression given. The if statement for this then becomes:

if (!preg_match('/^[\p{L}-\.\'\ ]+$/u', $name)) :
	$formerror = TRUE;
endif;

Check Required Fields

Any form should have a set of required fields, else anyone could submit an empty form and waste your time. The form markup from last week had the name, email and message as required fields. We could just simply have an if statement checking that each of these fields contain a value eg.

if (empty($_POST['cfname']) || empty($_POST['cfemail']) || empty($_POST['cfmessage'])) :
$formerror = TRUE;
endif;

Or alternatively, to allow for easy future additions of required fields, we could just have an array of required fields near the top of the page, to save you hunting for the correct statement to modify, and just run this array through a loop to check if each item had content eg.

// specify the required fields
$req_fields = array("cfname", "cfemail", "cfmessage");
// check required fields are completed
foreach ($req_fields AS $formlabel) :
$value = trim($_POST[$formlabel]);
if (empty($value)) :
$formerror = TRUE;
endif;
endforeach;

To then add another required field would then just require adding the name to the end of the array.

The PHP code here uses a foreach statement to loop through each array value. It then trims all whitespace off the form value, checks if the final value is empty or not. If it is then the $formerror is set to true. If all required fields have got a value then the $formerror will go unchanged (we’ll set this to false at the start of the PHP code when we come to put it all together).

Conclusion

This post has covered the validation routines that we need to implement to keep our form secure from abuse by spammers, and also to prevent mistakes from happening and forms being submitted too early. Understanding the regular expressions and the patterns used isn’t essential. They’re not the easiest things to understand when you don’t know where to start! However, they should cover most if not all possibilities so shouldn’t require changing in the future, unless the longest TLD becomes longer than 6 characters!

Next week I’ll go through the actual emailing of the form content along with additional information, and then we’ll be putting it all together.

Written by Sarah from Stuff By Sarah on August 31, 2008 | Filed Under WordPress Coding & Design

Share with others

  • StumbleUpon
  • Add to Delicious
  • Mixx
Make money with LinkXL

3 Responses so far | Have Your Say!

  1. dave  |  September 2nd, 2008 at 3:58 pm #

    dave - Gravatar

    Great tutorial, thank you.
    I was waiting for the processing/emailing part after I read the first tutorial in this series last week but don’t mind waiting till next Sunday, wish I didn’t have to though…

  2. Sarah (Post Author)   |  September 2nd, 2008 at 4:24 pm #

    Sarah - Gravatar

    Sorry! The sections of the contact form need a reasonable explanation (I wish it was easy as saying ‘it works, trust me’!), so it’s been broken down into manageable sections. It’ll all come together on Sunday, I promise! :)

  3. dave  |  September 2nd, 2008 at 4:38 pm #

    dave - Gravatar

    Thanks Sarah,
    I’m not complaining at all, can see why you are doing it this way & really appreciate you writing this stuff up.
    I just recently converted one of my sites to wordpress & need a bunch of these type of forms with proper validation so this lesson was fantastic.
    I’d prefer not to use plugins for something that should be simple enough to do, so eagerly awaiting the next post.

Trackbacks to 'Create a Contact Page Part II'

Leave Feedback

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>