PHP Email Validation 12,082 views

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.

 1<?php 2function check_email($email) { 3    $err = ''; 4 5    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 6        return 'Invalid email format'; 7    } 8 9    list($alias, $host) = explode("@", $email);1011    if (!checkdnsrr($host, "MX")) {12        return 'No MX record/invalid domain';13    }1415    getmxrr($host, $mxhosts);16    $connected = false;1718    foreach ($mxhosts as $mxhost) {19        $socket = @fsockopen($mxhost, 25, $errno, $errstr, 10);20        if ($socket) {21            $connected = true;22            break;23        }24    }2526    if (!$connected) {27        return 'Cannot connect to email server';28    }2930    $out = fgets($socket, 1024);31    if (!preg_match("/^220/", $out)) {32        fclose($socket);33        return 'No response from server';34    }3536    fwrite($socket, "HELO $host\r\n");37    fgets($socket, 1024);3839    fwrite($socket, "MAIL FROM: <{$email}>\r\n");40    $from = fgets($socket, 1024);4142    fwrite($socket, "RCPT TO: <{$email}>\r\n");43    $to = fgets($socket, 1024);4445    fwrite($socket, "QUIT\r\n");46    fclose($socket);4748    if (!preg_match("/^250/", $from) || !preg_match("/^250/", $to)) {49        return 'Server rejected address';50    }5152    return $err;53}