I have written some PHP to make WHOIS queries and return the retrieved WHOIS record.
The code is an excerpt from a much larger program used for monitoring domain name expiry. It's a command-line program designed to be run in a shell such as Bash or PowerShell, and has no web services involved.
Firstly, there is a function to identify the first-level TLD for the domain:
//Return the first-level TLD for a domain
function getTld($domain) {
//If domain contains dot, find first-level TLD and return it
if(strpos($domain, ".")) {
return(pathinfo($domain, PATHINFO_EXTENSION));
//If domain doesn't contain a dot, just return domain as-is
} else {
return($domain);
}
}
Then, the first-level TLD is prepended to .whois-servers.net
, and a WHOIS lookup is made to it over TCP port 43:
//Return raw WHOIS data for domain
function whois($domain) {
$whoisServer = getTld($domain) . ".whois-servers.net";
set_error_handler("whoisWarningHandler", E_WARNING);
$whois = fsockopen($whoisServer, 43);
restore_error_handler();
stream_set_timeout($whois, 3);
stream_set_blocking($whois, false);
fwrite($whois, $domain . "\r\n");
$read = [$whois]; $retries = 1; $null = null;
while(stream_select($read, $null, $null, 5) === false) {
if($retries++ >= 5) {
return(0);
}
print("Retrying... (attempt " . $retries . ")");
sleep(1);
}
sleep(1);
return(filter_var(fread($whois, 65535), FILTER_DEFAULT, FILTER_FLAG_STRIP_HIGH));
}
Finally, there is a custom warning handler to terminate the program if a connection to the WHOIS server cannot be established:
//Custom warning handler for WHOIS fsock/stream
function whoisWarningHandler($errno, $errstr) {
print("An error occurred while connecting to the WHOIS server.\n\nError output:\n\n" . $errstr . "\n");
exit(2);
}
The code may then be called using e.g. print(whois("example.com"));
, which would print the WHOIS record for example.com
.
Please could anyone advise as to whether best practise for code quality, efficiency and security has been followed, and any recommended adjustments/improvements that could be made?