Core Coding®

PHP Email Validation

  PHP Email Validation
Verify an email address in PHP by first checking for proper format. It then checks the domain mx records. Lastly it connects to the domain and verifies that the account exists.
function check_email($email) {
    
$err '';

    if (!
filter_var($emailFILTER_VALIDATE_EMAIL)) {
        return 
'Invalid email format';
    }

    list(
$alias$host) = explode("@"$email);

    if (!
checkdnsrr($host"MX")) {
        return 
'No MX record/invalid domain';
    }

    
getmxrr($host$mxhosts);
    
$connected false;

    foreach (
$mxhosts as $mxhost) {
        
$socket = @fsockopen($mxhost25$errno$errstr10);
        if (
$socket) {
            
$connected true;
            break;
        }
    }

    if (!
$connected) {
        return 
'Cannot connect to email server';
    }

    
$out fgets($socket1024);
    if (!
preg_match("/^220/"$out)) {
        
fclose($socket);
        return 
'No response from server';
    }

    
fwrite($socket"HELO $host\r\n");
    
fgets($socket1024);

    
fwrite($socket"MAIL FROM: <{$email}>\r\n");
    
$from fgets($socket1024);

    
fwrite($socket"RCPT TO: <{$email}>\r\n");
    
$to fgets($socket1024);

    
fwrite($socket"QUIT\r\n");
    
fclose($socket);

    if (!
preg_match("/^250/"$from) || !preg_match("/^250/"$to)) {
        return 
'Server rejected address';
    }

    return 
$err;
}

Go back to resources
Home Mail GitHub