PSBailey.co.uk - homepage

Email Address Validation (PHP)


Note: This article is also available as an ASP article.

It’s something that every site maker will have to worry about at some point or other — how to capture accurate email addresses. Luckily, with a scripting language like PHP or ASP it becomes much easier. So, without further ado, here is a function to validate email addresses in PHP. Instructions for how to call it are below.

NOTE: » indicates a line break.

<?php
//check if an email follows the format: a@aa.aa
//returns true or false.
function validemail($address) {
  if (eregi("^[[:alnum:]_'~\-\.]+@[[:alnum:]\-\.] »
  {2,}\.[[:alnum:]]{2,4}$",$address)) {
    return true;
  } else {
    return false;
  }
}
?>

How It Works

Regular expressions are handy little blighters. They are very good at spotting patterns in strings of text, and this is exactly what they have done here. It will look for [at least one alphanumeric character, single quote, tilda, dash or full stop] followed by [an @ symbol] followed by [ at least 2 alphanumeric characters, dash or full stop] followed by [a full stop] followed by [between 2 and 4 alpanumeric characters]. This is by no means bullet proof, a user could still enter 11@11.11 for instance, and that would be perfectly valid. This should not be your only line of defence against bogus email addresses, but it’s a good start.

In case you're thinking you’ll never get a user with a single quote in their email name, wait till you get john_o'reilly@aol.com. AOL is one of a few ISPs who have bucked the trend and allowed them through. It’s a good idea to fix these addresses before you go adding them to your database too, as the single quote could break your carefully constructed SQL statements. Consider using addslashes(). You have been warned.

Note: Regular expressions should only be used when there is a significant gain over PHP’s traditional string manipulation functions. They are generally are not as fast as a line or two of standard stuff, but in this case the saving will be 10-15 lines of code so it is as quick as standard methods.

How To Call It

This function will only need to be defined once for any page of PHP, or better still put into an include file for use throughout the website. It is called like so:

<?php

$email_from_user = 'foo@madeupaddress';

if (validemail($email_from_user)) {
  echo 'Thanks for a valid email address.';
} else {
  echo 'That aint no valid address punk!!!';
}
?>

You can download a fully working example to play with at your leisure. Just place the enclosed files on a PHP enabled environment and you’re away. This article is also available as an ASP article.

Feel free to use this code any way you like, however, a link to my site (this page or any other) would be very much appreciated in return. Thanks.

Get Firefox! Valid XHTML Valid CSS