Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple SMTP email validation function for php? Also, is it worth it?

Tags:

php

email

Does anybody have a good function for validating email addresses by SMTP in PHP? Also, is it worth it? Will it slow down my server?

--> EDIT: I am referring to something like this:

http://onwebdevelopment.blogspot.com/2008/08/php-email-address-validation-through.html

which is meant to complement validation of the syntax of the email address.

It looks complicated though, and I was hoping there was a simpler way of doing this.

like image 212
chris Avatar asked Oct 15 '22 15:10

chris


1 Answers

If you want to check if there is a mail exchanger at the domain, you can use something like this:

/*checks if email is well formed and optionally the existence of a MX at that domain*/
function checkEmail($email, $domainCheck = false)
{
    if (preg_match('/^[a-zA-Z0-9\._-]+\@(\[?)[a-zA-Z0-9\-\.]+'.
                   '\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/', $email)) {
        if ($domainCheck && function_exists('checkdnsrr')) {
            list (, $domain)  = explode('@', $email);
            if (checkdnsrr($domain, 'MX') || checkdnsrr($domain, 'A')) {
                return true;
            }
            return false;
        }
        return true;
    }
    return false;
}

Usage:

$validated = checkEmail('[email protected]', true);
like image 197
karim79 Avatar answered Nov 04 '22 00:11

karim79