|
<?php |
|
class SubDomains { |
|
protected static $tlds = array(); |
|
|
|
const TLD_URL = 'http://data.iana.org/TLD/tlds-alpha-by-domain.txt'; |
|
const COMMENT_CHARACTER = '#'; |
|
|
|
/** |
|
* Fetches domains from data.iana site |
|
*/ |
|
public static function initTLds() { |
|
$file = fopen(static::TLD_URL, 'r'); |
|
if(!$file) throw new Exception('Unable to open TLD source'); |
|
|
|
while(!feof($file)){ |
|
$line = trim(fgets($file)); |
|
|
|
if(substr($line, 0, 1) == static::COMMENT_CHARACTER) continue; |
|
|
|
$Tlds[] = strtolower($line); |
|
} |
|
} |
|
|
|
/** |
|
* @param string $domain Domain of the URL |
|
* @return array Each subdomain item in turn |
|
*/ |
|
public static function getSubDomains($domain){ |
|
$parts = explode('.', $domain); |
|
$current_domain = static::createDomain($parts); |
|
|
|
$domains = array($current_domain); |
|
for($i = count($parts); $i > 0; $i--){ |
|
$part = array_pop($parts); |
|
$current_domain = $part . '.' . $current_domain; |
|
$domains[] = $current_domain; |
|
} |
|
|
|
return array_reverse($domains); |
|
} |
|
|
|
/** |
|
* @param string $domain Domain of the URL |
|
* @return string The root domain (www.bbc.co.uk maps to bbc.co.uk) |
|
*/ |
|
public static function getRootDomain($domain){ |
|
$parts = explode('.', $domain); |
|
return static::createDomain($domain); |
|
} |
|
|
|
/** |
|
* @param string $subdomain The string to check |
|
* @return string If the string is a TLD |
|
*/ |
|
public static function isTld($subdomain){ |
|
return in_array($subdomain, static::$tlds); |
|
} |
|
|
|
/** |
|
* Finds the first instance of a non-tld url |
|
* @param array $parts Parts of the domain |
|
* @return string All elements of the domain upuntil that point |
|
*/ |
|
protected static function createDomain(&$parts){ |
|
$current_domain = array_pop($parts); |
|
$length = count($parts); |
|
|
|
for($i = 0; $i < $length; $i++){ |
|
$subdomain = array_pop($parts); |
|
$current_domain = $subdomain . '.' . $current_domain; |
|
|
|
if(!static::isTld($subdomain)) break; |
|
} |
|
|
|
return $current_domain; |
|
} |
|
} |