0

I have a problem with a section of my code. I created a dig, but now I'm trying to add A record directly on the MX record (eg MX record -> IP address).

I have this code for finding A record from the MX I already found:

$comm = 'dig @' . $ns . ' MX ' . $domain . ' +short';
$mx_dns = shell_exec ($comm);
$mx = explode(' ', $mx_dns); //explode to take only the MX and not the priority
$mx2 = substr($mx[1],0,-1); //removing dot (.) from MX

$comm = 'dig A ' . $mx2 . ' @' . $ns . ' +short';
$ip_mx = shell_exec ($comm);

print_r($mx);

if ($ip_mx == null)
{
    $comm = 'dig A ' . $mx . ' @8.8.8.8 +short';
    $ip_mx2 = preg_split('/\s+/', shell_exec ($comm)); //only take first IP
    $ip_mx = $ip_mx2[0];
}

In the above code, I ask for the DNS of the domain. If DNS doesn't respond A record, I want to ask Google (8.8.8.8).

In the print_r, I found that if a domain has more than one MX record (eg google.com), everything breaks down. If the domain has one MX only, the dig works fine.

The problem is, that my explode function, works with one MX. With more than one MX, the table I have, has also the next priority (eg the priority from second MX).

If I try to fix this, then the script can't find IP address for all the domains that has one MX.

Can you please help me with this?

Thank you very much in advance all of you.

adamkwn
  • 49
  • 9
  • Perhaps you need to `$mx_dns = explode("\n" trim($mx_dns))[0];` to take the first row of a multi-value dns lookup (or only row of a single value return) – Michael Berkowski Oct 21 '17 at 16:10
  • Finally, I thought PHP might have a native function: [`print_r(dns_get_record('your.domain.example.com', DNS_MX))`](http://php.net/manual/en/function.dns-get-record.php) – Michael Berkowski Oct 21 '17 at 16:15
  • @MichaelBerkowski thank you very much for your help. It worked using: $mx_dns = explode("\n", trim($mx_dns))[0]; – adamkwn Oct 23 '17 at 04:14

0 Answers0