您的位置:首页 > 编程语言 > PHP开发

用PHP验证邮箱有效性

2010-06-21 17:57 405 查看
在sitepoint挖到一篇Verify a User’s Email Address Using PHP,本来打算自己翻译一下,学习一下。所以翻PHP Funtion查找当中出现的函数,无意中就发现checkdnsrr函数那里就有了更精妙的例子,分享给大家!
<?php

function validate_email($email){
$exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息