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:
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).
- Error Handling:
- If no A records are found, the function throws a
RuntimeException
.
- If no A records are found, the function throws a
- Result Parsing:
- The
dns_get_record()
function returns an array of records. - Each record includes details such as
host
,class
,ttl
, andip
(the IPv4 address).
- The
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