Search code examples
phpmx-record

DNS_GET_RECORD MX lookup failing in PHP script


I have a PHP script that is using get_dns_record to retrieve and display specific DNS records for a domain, submitted via a form.

It's working really well, except that the section that handles MX records is a little unreliable. Sometimes no MX Records are displayed at all (on domains I know have them). If you refresh 2-3 times, sometimes they will show up. Sometimes they won't.

function getDNSRecord($domain1) {
    $dns = dns_get_record( $domain1, DNS_ANY );
    echo "These are DNS records";
    foreach( $dns as $d ) {
        // Only print A and MX records
        if( $d['type'] != "A" and $d['type'] != "MX" )
            continue;
    
        // Print type specific fields
        switch( $d['type'] ) {
            case 'A':
                // Display annoying message
                echo "<b>\n" . $d['ip'] . "</b>\n is the Primary A Record for this domain.";
                break;
            case 'MX':
                // Resolve IP address of the mail server
                $mx = dns_get_record( $d['target'], DNS_A );
                foreach( $mx as $server ) {
                    echo "This MX record for " . $d['host'] . " points to the server <b>\n" . $d['target'] . "</b>\n whose IP address is <b>\n" . $server['ip'] . "</b>. It has a priority of <b>\n" . $d['pri'] . "</b>\n.";
                }
            if ( $d['target'] == $domain1 ) {
                echo "<div id='mx-status'>There is an issue with this MX Record</div>\n";
                    } else {
                echo "<div id='mx-status'>This MX Record looks fine.</div>\n";
                }
                break;
        }
    }
}

Solution

  • Have you considered using getmxrr() to get the mx records for the domain? Documentation here: https://www.php.net/manual/en/function.getmxrr.php