View Tutorial Metadata Edit Content Revision History Add to Watchlist Add New Tutorial How to check if an email address is valid in PHP

How to check if an email address is valid in PHP

To test an email address if valid is not as easy as it seems.

Here is a function that can do this partially : by validating its format and then by checking if the domain it uses has any MX records registered on the DNS.

function checkEmail($email){
	//check email format
	if (filter_var($email, FILTER_VALIDATE_EMAIL) == $email){
		//check if the domain has MX entries
		$aux = explode('@',$email);
		return checkdnsrr($aux[1],'MX');
	}
	return false;
}

What isn't covered in this check :

  • There is no check that the actual username really exists.

If you are on Windows hosting you need to add the next 2 functions as well, as the checkdnsrr function isn't native available here :

//THESE FUNCTIONS WERE TAKEN FROM PHP.NET WEBSITE
function win_checkdnsrr($host, $type='MX') {
    $types=array('A', 'MX', 'NS', 'SOA', 'PTR', 'CNAME', 'AAAA', 'A6', 'SRV',
'NAPTR', 'TXT', 'ANY');
    if (!in_array($type,$types)) {
        user_error("checkdnsrr() Type '$type' not supported", E_USER_WARNING);
        return;
    }
    @exec('nslookup -type='.$type.' '.escapeshellcmd($host), $output);
    foreach($output as $line){
        if (preg_match('/^'.$host.'/',$line)) { return true; }
    }
	return false;
}
 
 
function checkdnsrr($host, $type='MX') {
	return win_checkdnsrr($host, $type);
}

Only plain text supported.

Optional

Required - will be kept private

Optional

 
 

Rating: (0+, 0-) In: PHP 5