星期一, 9月 26, 2005

Valid email address correctly (PHP)

Nowadays, valid the format of the email is not enough, so, we need to valid it with making a testing connection to the email server and ask the email server that the user provided if the email account exisit! Here is a PHP function that can do this for you:
<?php

/* Return value: (true|false)
   true if valid, false if invalid */

function valid_email($email)
{
    global
$HTTP_HOST;

    if (!
eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $email)) {       
        return
false;
    }

    list(
$username,$domain) = split("@",$email);

    if (
checkdnsrr($Domain,"MX")) {
        
getmxrr ($Domain, $mxhost);
        
$host = $mxhost[0];
    }
    else {
        
$host = $domain;         
    }

    
$connect = fsockopen($host,25};
    if (
$connect) {
        if (
ereg("^220", $returns=fgets($connect,1024))) {
            
fputs($connect,'HELO ' . $HTTP_HOST . "\r\n");
            
$returns = fgets ($connect,1024);
            
fputs($connect,'MAIL FROM: <' . $email . ">\r\n");
            
$test1 = fgets($connect,1024);
            
fputs ($connect,'RCPT TO: <' . $email . ">\r\n");
            
$test2 = fgets($connect,1024);
            
fputs ($connect,"QUIT\r\n");
            
fclose($connect);
            if ((!
ereg("^250",$test1)) or (!ereg("^250",$test2))) {
                return
false;
            }
        }
    }
    else {
        return
false;
    }
    return
true;
}

?>

沒有留言: