Skip to content

Instantly share code, notes, and snippets.

@cam-gists
Created August 20, 2012 16:00
Show Gist options
  • Select an option

  • Save cam-gists/3405367 to your computer and use it in GitHub Desktop.

Select an option

Save cam-gists/3405367 to your computer and use it in GitHub Desktop.
PHP: Strict Email VAlidation
<?php
/*
Email Address Validation
Check the variable $email is a valid email address.
Usage:
print validate_email("email@address.com");
Or:
$email = "email@address.com";
print validate_email($email);
*/
function validate_email($email) {
if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email)) {
$return = "$email is not an email address.";
}
$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 = "$email is not an email address.";
}
}
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 = "$email is not an email address.";
}
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 = "$email is not an email address.";
}
}
}
$return = "$email is valid email address.";
return $return;
}
<?php
$email="test@geemail.com";
if (isValidEmail($email))
{
echo "Hooray! Adress is correct.";
}
else
{
echo "Sorry! No way.";
}
//Check-Function
function isValidEmail($email)
{
//Perform a basic syntax-Check
//If this check fails, there's no need to continue
if(!filter_var($email, FILTER_VALIDATE_EMAIL))
{
return false;
}
//extract host
list($user, $host) = explode("@", $email);
//check, if host is accessible
if (!checkdnsrr($host, "MX") && !checkdnsrr($host, "A"))
{
return false;
}
return true;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment