scaoping 发表于 2017-4-1 07:15:30

用PHP验证邮箱有效性

  在sitepoint挖到一篇Verify a User’s Email Address Using PHP,本来打算自己翻译一下,学习一下。所以翻PHP Funtion查找当中出现的函数,无意中就发现checkdnsrr函数那里就有了更精妙的例子,分享给大家!
  function validate_email($email){   
$exp = "^+([._-]+)*@(+([._-]+))+$";   
if(eregi($exp,$email)){ //先用正则表达式验证email格式的有效性   
if(checkdnsrr(array_pop(explode("@",$email)),"MX")){//再用checkdnsrr验证 email的域名部分的有效性   
return true;   
}else{   
return false;   
}   
}else{   
return false;   
}   
}   
?>   
注意:checkdnsrr函数在win主机上是无效的!!
  Verify a User’s Email Address Using PHP中提出了另一种解决办法,写自己的函数:
  function myCheckDNSRR($hostName, $recType = '')   
{   
if(!empty($hostName)) {   
if( $recType == '' ) $recType = "MX";   
exec("nslookup -type=$recType $hostName", $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("^$hostName",$line)) {   
return true;   
}   
}   
// otherwise there was no mail handler for the domain   
return false;   
}   
return false;   
}
页: [1]
查看完整版本: 用PHP验证邮箱有效性