Email validation with PHP
February 17, 2008
An important issue when handling data input from a website's visitors is validating the information the user submits, so that it complies with your specifications and needs. If, for the most part, this means setting up your own set of rules and writing code accordingly, one aspect that you can get away with by implementing an existing function is e-mail address validation.
There are quite a few of functions out there written for just this purpose, this is just one of them, that I've found to be doing the job quite nicely and thoroughly.
function check_email_address($email) {
// First, we check that there's one @ symbol, and that the lengths are right
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
// Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
return false;
}
// Split it into sections to make life easier
$email_array = explode("@", $email);
$local_array = explode(".", $email_array[0]);
for ($i = 0; $i < sizeof($local_array); $i++) {
if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i])) {
return false;
}
}
if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1])) { // Check if domain is IP. If not, it should be valid domain name
$domain_array = explode(".", $email_array[1]);
if (sizeof($domain_array) < 2) {
return false; // Not enough parts to domain
}
for ($i = 0; $i < sizeof($domain_array); $i++) {
if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i])) {
return false;
}
}
}
return true;
}
The most basic PHP email address validation function can give its ok on patterns such as user@domain.com, but problems might arise with emails such as info@school.vic.edu.au. This function however validates these just fine.
A simple example of using the function is shown below:
if (!check_email_address($email)) {
echo "This is not a valid e-mail address!";
}
else {
echo "Valid!";
}
Labels: email, function, php, validation
1 comments:
Subscribe to:
Post Comments (Atom)
this is verry good one you can look
http://www.phpcodebook.com for more and updated php codes