How to request an A record from a DNS server in PHP 8.3

In PHP 8.3, you can use the dns_get_record() function to query DNS records, including A records. Here’s an example of how to request an A record from a DNS server:

<?php
function getARecord(string $hostname): array {
    // Fetch A records for the given hostname
    $records = dns_get_record($hostname, DNS_A);

    if ($records === false || empty($records)) {
        throw new RuntimeException("No A records found for $hostname.");
    }

    return $records;
}

// Example usage
try {
    $hostname = "example.com";
    $aRecords = getARecord($hostname);

    echo "A records for $hostname:\n";
    foreach ($aRecords as $record) {
        echo " - IP Address: " . $record['ip'] . "\n";
    }
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}
?>

Explanation:

  1. dns_get_record():
    • This function queries DNS records for the specified hostname.
    • The second parameter DNS_A limits the query to A records (IPv4 addresses).
  2. Error Handling:
    • If no A records are found, the function throws a RuntimeException.
  3. Result Parsing:
    • The dns_get_record() function returns an array of records.
    • Each record includes details such as host, class, ttl, and ip (the IPv4 address).

Example Output:

If the domain has A records, the output will look like this:

A records for example.com:
 - IP Address: 93.184.216.34

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *