Skip to content

Instantly share code, notes, and snippets.

@skylerkatz
Created February 2, 2018 17:07
Show Gist options
  • Save skylerkatz/aab9486bbb36940d4413738a1bd74ce9 to your computer and use it in GitHub Desktop.
Save skylerkatz/aab9486bbb36940d4413738a1bd74ce9 to your computer and use it in GitHub Desktop.
A quick and dirty PHP wrapper around the dig command for basic DNS inforamtion about a domain.
<?php
class DnsLookup
{
public static function dig($url)
{
$host = $url;
$digClassArray = ['A', 'MX', 'NS', 'SOA', 'CNAME'];
$finalOutput = [];
foreach ($digClassArray as $digClass) {
$command = "dig $host $digClass +noall +answer";
$results = shell_exec("$command");
$results = explode(PHP_EOL, $results);
$results = array_filter($results, function ($result) {
return strpos($result, "\t") !== false;
});
foreach ($results as $answer) {
$answer = explode("\t", $answer);
$answer = array_filter($answer);
$answer = array_values($answer);
if (!array_key_exists(4, $answer)) {
if (strpos($answer[0], ' ')) {
$build = explode(' ', $answer[0]);
if (array_key_exists(3, $build) && $build[3] === 'A') {
array_push($build, $answer[1]);
}
if (array_key_exists(1, $answer) && $answer[1] === 'CNAME') {
$build = [
0 => $build[0],
1 => '',
2 => '',
3 => $answer[1],
4 => $answer[2],
];
}
$answer = $build;
}
}
$answer = [
'Domain' => $answer[0],
'Type' => $answer[3],
'Result' => $answer[4],
];
$finalOutput[] = $answer;
}
}
if (empty($finalOutput)) {
throw new \Exception('Domain Name Error');
}
$finalOutput = array_map('unserialize', array_unique(array_map('serialize', $finalOutput)));
$output = ['Results' => $finalOutput];
return $output;
}
}
echo '<pre style="background-color:white; "><code style="color:black;">';
var_dump(DnsLookup::dig('google.com'));
echo '</pre></code>';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment