In this example, you will learn about the DNS look function in PHP and how to use it. For demonstration purpose, we will create a simple HTML form which takes domain name from as the user input. The form will be submitted to practice_ac.php which contains the PHP code to lookup the DNS record of the domain being submitted.

DNS lookup function in PHP

Now let’s create a simple webpage using the HTML and CSS below

<div class="form_box shadow">
   <form action="practice_ac.php" method="post">
     <h4>DNS LookUp</h4>
     <p>Enter Domain Name please</p>
     <input type="text" name="domain" value="www.tutorialspanel.com"><br/>
     <input type="submit" name="submit" value="GO">
   </form>
 </div>

And the CSS

.form_box{width:400px; padding:20px; background-color:white;}
input{padding:5px; width:100%; margin:5px 0;}

DNS Lookup Form

dns_get_record() function

In this example we are going to use the built-in function dns_get_record() function. This function was introduced in PHP 5 to fetch DNS resource records associated with a hostname.

The Syntax

dns_get_record ( string $hostname [, int $type = DNS_ANY [, array &$authns [, array &$addtl [, bool $raw = FALSE ]]]] ) : array

The Parameters

$hostname – It should be a valid DNS hostname such as www.tutorialspanel.com.
$type – It will search for any resource records associated with hostname. By default, the value is DNS_ANY
$auhns – Note & with $authns variable. This parameter is passed by reference and, if given, will be populated with Resource Records for the Authoritative Name servers.
$addtl – To pass any additional records
$raw – If set as true, dns_get_record() function will return only the requested type instead of looping type by type.

Example of dns_get_record() function

  <pre>
    <?php
    $d = $_POST['domain'];
    $result = dns_get_record($d);
    print_r($result);
    ?>
  </pre>

The result of DNS Lookup

As you can see, the [host] is the record to which the rest of the associated data refers. Class attribute only returns Internet class records and so always return IN. Type attribute contains record type. TTL attribute is Time to Live remaining for this record.

The only drawback with this function is its inability to handle the error. It simply returns out true on success and false on failure.

gethostbyaddr() function

If you need to find the name of the server, use gethostbyaddr() function

<?php
$result = dns_get_record("www.yahoo.com", DNS_A);
$host =gethostbyaddr($result[0]['ip']) ;
echo $host;
?>

Server Name

Recommended Reading

Last modified: March 23, 2019