29 October 2008

How to Verify Email Address Using PHP

At the previous article, we have already know how to run a PHP mail application in localhost. Now, this tutorial will show you how to verify an email address using PHP, it is in valid format or not. Please note, this article only show how to check the format, not the existence of the URL or the service provider.

To verify an email address format using PHP is easy, PHP has a great function called eregi. This is a part of PHP form validation for other entries to check proper formatted data is entered by the user.

The first step to creating a PHP script for validating an email address is work, it is good to know what characters are allowed and what characters are not allowed in an email address, states that the form of an email address must be of the form "user_account@domain". The "user_account" of an email address must be between 1 and 64 characters in length and may be made up in any one of three ways. It can be made up of a selection of characters (and only these characters) from the following selection:

  • A to Z
  • 0 to 9
  • !
  • #
  • $
  • %
  • &
  • '
  • *
  • +
  • -
  • /
  • =
  • ?
  • ^
  • _
  • `
  • {
  • }
  • ~
  • .

The "domain" of the email address can also be made up in different ways. The most common form is a domain name, which is made up of a number of "labels", each separated by a period and between 1 and 63 characters in length. Labels may contain letters, digits and hyphens, however must not begin or end with a hyphen (officially, a label must begin with a letter, not a digit, however many domain names have been registered beginning with digits so for the purposes of validation we will assume that digits are allowed at the start of domain names). A domain name, technically, need be only one label.

When you register on at a website, the site normally checks if the e-mail address that you enter is in a valid format. This is done by using what called a Regular Expression. What we need to do is check if a string matches the regular expression.

This example is using ereg function with the regular expression:


<form method=post action=<?php $_SERVER['PHP_SELF']; ?>>
Your email : <input name="email" type="text">
<input type="submit" name="check" value="Check E-Mail">
</form>

<?php>
if ($_POST[check]);
{
$valid_mail = "^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9]+)(\.[a-z]{2,3}))$"; //regular expression
if (!eregi($valid_mail,$email))
{
echo "Your email address is NOT VALID";
}
else
{
echo "Your email address is valid";
}
}
?>



Now, You can validate email addresses entered into your site.
Good Luck


References:
Lukmanul Hakim, Loko Media
http://www.addedbytes.com/
http://www.codewalkers.com/
http://www.plus2net.com/

No comments: