Skip to content

Instantly share code, notes, and snippets.

@finalwebsites
Last active April 9, 2016 06:07
Show Gist options
  • Save finalwebsites/e19c6b72f70d0f3caa9701b8d8988983 to your computer and use it in GitHub Desktop.
Save finalwebsites/e19c6b72f70d0f3caa9701b8d8988983 to your computer and use it in GitHub Desktop.
Extract the TLD from a domain name, PHP tutorial code from http://www.tutdepot.com/parse-url-extract-domain-name/
<?php
$url_parts = parse_url("http://mail.finalwebsites.co.uk");
$domain = $url_parts['host'];
$db = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$res = $db->query("SELECT tld FROM domain_info ORDER BY LENGTH(tld) DESC");
// "ORDER BY LENGTH(tld)" will give first the co.uk and then the uk
while ($arr = $res->fetch_array(MYSQLI_ASSOC)) {
$tmp_tld = substr($domain, -strlen(".".$arr['tld']));
if ($tmp_tld == ".".$arr['tld']) { // You found the tld
$tld = ltrim($arr['tld'], ".");
$domainLeft = substr($domain, 0, -(strlen($tld) + 1)); // It will left the whatever, without the extension and the .
if (strpos($domainLeft, ".") === false) { // It hasn't a subdomain
$subDomain = "";
$finalDomain = $domainLeft;
} else {
$domain_parts = explode(".", $domainLeft);
$finalDomain = array_pop($domain_parts); // select the domain and remove it from the array
$subDomain = implode(".", $domain_parts); // a subdomain can more then one parts seperated with dot's
}
echo "The tld is: ".$tld."<br>";
echo "the domain name is :".$finalDomain."<br />";
echo "the subdomain is: ";
echo (!empty($subDomain)) ? $subDomain : "n/a";
echo "<br>";
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment