用PHP验证邮箱有效性

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

  1. < ?php
  2.  
  3. function validate_email($email){
  4.  
  5. $exp = "^[a-z'0-9]+([._-][a-z'0-9]+)*@([a-z0-9]+([._-][a-z0-9]+))+$";
  6.  
  7. if(eregi($exp,$email)){ //先用正则表达式验证email格式的有效性
  8.  
  9. if(checkdnsrr(array_pop(explode("@",$email)),"MX")){//再用checkdnsrr验证email的域名部分的有效性
  10. return true;
  11. }else{
  12. return false;
  13. }
  14.  
  15. }else{
  16.  
  17. return false;
  18.  
  19. }
  20. }
  21.  
  22. ?>

注意:checkdnsrr函数在win主机上是无效的!!

Verify a User’s Email Address Using PHP中提出了另一种解决办法,写自己的函数:

  1. function myCheckDNSRR($hostName, $recType = '')
  2. {
  3. if(!empty($hostName)) {
  4. if( $recType == '' ) $recType = "MX";
  5. exec("nslookup -type=$recType $hostName", $result);
  6. // check each line to find the one that starts with the host
  7. // name. If it exists then the function succeeded.
  8. foreach ($result as $line) {
  9. if(eregi("^$hostName",$line)) {
  10. return true;
  11. }
  12. }
  13. // otherwise there was no mail handler for the domain
  14. return false;
  15. }
  16. return false;
  17. }

留言

提示/Tips:中国人使用中文!Your comment must include some Chinese in order to pass the comment checking.