How to query DNS records using PHP
dns_get_record() function
This function actually gets us the actual DNS records data in a nice array that we can work with. The function also has a few parameters that we can use as before:
- hostname – This would need to be a valid DNS hostname, for instance “google.com”.
- type – This is the type of query we want to make, for instance we have the following options:
- DNS_A, DNS_CNAME, DNS_HINFO, DNS_MX, DNS_NS, DNS_PTR, DNS_SOA, DNS_TXT, DNS_AAAA, DNS_SRV, DNS_NAPTR, DNS_A6, DNS_ALL or DNS_ANY
- authns – if used, this variable will be populated with Resource Records for the Authoritative Name Servers.
- addtl – if used, this variable will be populate with any Additional Records
- raw – if used, we query only the requested type instead of looping type by type before going with the additional info stuff.
In most application, I found this to be mostly used or the previous function, the first one provides you with a simple ‘yes’ or ‘no’ if a dns record exists and the dns_get_record() function will get you the actual data for the specific hostname.
Code example:
1 2 |
$get_any_records = dns_get_record("google.com", DNS_NS+DNS_MX); print_r($get_any_records); |
Output of this would be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
Array ( [0] => Array ( [host] => google.com [type] => NS [target] => ns2.google.com [class] => IN [ttl] => 53783 ) [1] => Array ( [host] => google.com [type] => NS [target] => ns4.google.com [class] => IN [ttl] => 53783 ) [2] => Array ( [host] => google.com [type] => NS [target] => ns3.google.com [class] => IN [ttl] => 53783 ) [3] => Array ( [host] => google.com [type] => NS [target] => ns1.google.com [class] => IN [ttl] => 53783 ) [4] => Array ( [host] => google.com [type] => MX [pri] => 40 [target] => alt3.aspmx.l.google.com [class] => IN [ttl] => 600 ) [5] => Array ( [host] => google.com [type] => MX [pri] => 10 [target] => aspmx.l.google.com [class] => IN [ttl] => 600 ) [6] => Array ( [host] => google.com [type] => MX [pri] => 30 [target] => alt2.aspmx.l.google.com [class] => IN [ttl] => 600 ) [7] => Array ( [host] => google.com [type] => MX [pri] => 50 [target] => alt4.aspmx.l.google.com [class] => IN [ttl] => 600 ) [8] => Array ( [host] => google.com [type] => MX [pri] => 20 [target] => alt1.aspmx.l.google.com [class] => IN [ttl] => 600 ) ) |
↠ Continue with getmxrr()