Skip to content

Instantly share code, notes, and snippets.

@lonnieezell
Created October 31, 2011 18:48
Show Gist options
  • Select an option

  • Save lonnieezell/1328435 to your computer and use it in GitHub Desktop.

Select an option

Save lonnieezell/1328435 to your computer and use it in GitHub Desktop.
Email Validation
/*
Method: valid_email()
Verifies that an email could at least potentially be real
by verifying the domain accepts email it seems to be proper format.
Parameter:
$str - The email address to verify
Returns:
true/false
*/
public static function valid_email($str=null)
{
if (empty($str))
{
self::$error = 'You entered an empty email address.';
return false;
}
if (strpos($str, '@') === false)
{
self::$error = 'Your email does not appear to be valid.';
return false;
}
// Strip out any tags and compare to make sure
// we're not getting a script inserted.
$test = strip_tags($str);
if ($test !== $str)
{
self::$error = 'Your email does not appear to be valid.';
return false;
}
// Check that the domain exists
list($username, $domain) = explode('@', $str);
if (empty($username) || empty($domain))
{
self::$error = 'Your email does not appear to be valid.';
return false;
}
/*
If you are using Windows hosting, you will need to
uncomment the following line and comment out the
existing if() below.
*/
// if (!self::check_dns($domain))
if (!checkdnsrr($domain, 'MX'))
{
self::$error = 'Your email does not appear to be valid.';
return false;
}
return true;
}
//--------------------------------------------------------------------
/*
Method: check_dns()
A dns lookup function that works only on Windows.
Parameters:
$domain - The domain name or IP address to lookup.
$record_type - The record type to lookup. Defaults to 'MX' for email.
*/
private static function check_dns($domain=null, $record_type='MX')
{
if (empty($domain))
{
return false;
}
exec("nslookup -type=$recType $domain", $result);
// check each line to find the one that starts with the host
// name. If it exists then the function succeeded.
foreach ($result as $line)
{
if(eregi("^$domain", $line)) {
return true;
}
}
// otherwise there was no mail handler for the domain
return false;
}
//--------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment