PHP: cross-platform email validation

An important part of email validation is to check if an host is alive or not. On a Unix platform this can be easily achieved with the PHP's getmxrr() function. Unfortunately, this function is not available on Windows. For that reason, I ran an extensive search on the web to find a script that performs this task in a cross-platform fashion and I found the following script by Setec Astronomy (released under the GPL license):

function getmxrr_win ($hostname = "", &$mxhosts, &$weight)
 $weight = array();
 $mxhosts = array();
 $result = false;
 $command = "nslookup -type=mx " . escapeshellarg ($hostname);
 exec ($command, $result);
 $i = 0;
 while (list ($key, $value) = each ($result)) 
    if (strstr ($value, "mail exchanger")) 
    { $nslookup[$i] = $value; $i++; }
 while (list ($key, $value) = each ($nslookup)) 
    $temp = explode ( " ", $value );
    $mx[$key][0] = substr($temp[3],0,-1);
    $mx[$key][1] = $temp[7];
    $mx[$key][2] = gethostbyname ( $temp[7] );
 array_multisort ($mx);
 foreach ($mx as $value) 
  $mxhosts[] = $value[1];
  $weight[] = $value[0];
 $result = count ($mxhosts) > 0;
 return $result;

function getmxrr_portable ($hostname = "", &$mxhosts, &$weight)
 if (function_exists ("getmxrr"))
 { $result = getmxrr ($hostname, $mxhosts, $weight); }
 { $result = getmxrr_win ($hostname, $mxhosts, $weight); }
 return $result; 

The first function uses the Windows shell to perform an MX lookup, while the second checks whether getmxrr() is available or not. If it is, then the standard PHP function will be used, otherwise the first function will be used.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.