Skip to content

PHP dns_get_record() Function: Everything You Need to Know

As a PHP developer, you may need to obtain various types of DNS records for a domain name. The dns_get_record() function is a built-in PHP function that allows you to retrieve these records.

⚠️ Deprecation Notice: dns_get_record() was deprecated in PHP 8.2 and removed in PHP 8.4. For modern PHP applications, consider using the getdns extension, system commands like dig or nslookup via shell_exec(), or third-party DNS libraries.

What is the dns_get_record() Function?

The dns_get_record() function retrieves various types of DNS records for a given domain name. It returns an array of DNS records based on the record type you specify.

How to Use the dns_get_record() Function

Using the dns_get_record() function is straightforward. Here is the syntax of the function:

The PHP syntax of dns_get_record() Function

php
dns_get_record($hostname, $type = DNS_ANY, &$authns = NULL, &$addtl = NULL);

The function takes four parameters:

  • $hostname: The domain name for which you want to retrieve the DNS records.
  • $type: The type of DNS record that you want to retrieve. This parameter is optional and defaults to DNS_ANY if not specified.
  • &$authns: A variable that stores the authoritative DNS nameservers for the domain.
  • &$addtl: A variable that stores additional information about the DNS records.

Here is an example of how to use the dns_get_record() function to retrieve the A and MX records for a domain name, while capturing the authoritative nameservers and additional records:

How to Use the dns_get_record() Function?

php
<?php

$domain = "example.com";
$authns = [];
$addtl = [];
$records = dns_get_record($domain, DNS_A | DNS_MX, $authns, $addtl);

print_r($records);

The function returns an array of associative arrays. Each element represents a DNS record and contains common keys like host, type, class, and ttl. Depending on the record type, it also includes type-specific keys such as ip (or ipv6), priority, target, txt, or ns.

Types of DNS Records

The dns_get_record() function can retrieve various types of DNS records. Here are some of the most common types:

  • A: Returns the IPv4 address of the domain name.
  • AAAA: Returns the IPv6 address of the domain name.
  • MX: Returns the mail exchange server for the domain name.
  • NS: Returns the name server for the domain name.
  • CNAME: Returns the canonical name for an alias.

Conclusion

The dns_get_record() function is a useful tool for retrieving various types of DNS records for a domain name. By understanding the syntax and usage of the function, you can easily obtain the DNS records that you need for your PHP application. We hope this article has been informative and useful in understanding the dns_get_record() function in PHP.

Practice

What is the purpose of the dns_get_record() function in PHP?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.