How to get second-level domain from URL in PHP

There is relatively easy way in PHP how to get the full URL of your actual page. But what to do if you need just a 2nd level domain name? Okay, let's see how to!

1) Get the full URL

if(isset($_SERVER['HTTPS'])) $protocol = 'https';
else $protocol = 'http';

$url = $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
Now when we have the full URL. We can call this function with the URL parameter.

2) Function which returns 2nd level domain name

function get2ndLvlDomainName($url)
{
 // a list of decimal-separated TLDs
 static $doubleTlds = [
  'co.uk', 'me.uk', 'net.uk', 'org.uk', 'sch.uk', 'ac.uk',
  'gov.uk', 'nhs.uk', 'police.uk', 'mod.uk', 'asn.au', 'com.au',
  'net.au', 'id.au', 'org.au', 'edu.au', 'gov.au', 'csiro.au',
  'br.com', 'com.cn', 'com.tw', 'cn.com', 'de.com', 'eu.com',
  'hu.com', 'idv.tw', 'net.cn', 'no.com', 'org.cn', 'org.tw',
  'qc.com', 'ru.com', 'sa.com', 'se.com', 'se.net', 'uk.com',
  'uk.net', 'us.com', 'uy.com', 'za.com'
 ];

 // sanitize the URL
 $url = trim($url);

 // check if we can parse the URL
 if ($host = parse_url($url, PHP_URL_HOST)) {

  // check if we have IP address
  if (preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $host)) {
   return $host;
  }

  // sanitize the hostname
  $host = strtolower($host);

  // get parts of the URL
  $parts = explode('.', $host);

  // if we have just one part (eg localhost)
  if (!isset($parts[1])) {
   return $parts[0];
  }

  // grab the TLD
  $tld = array_pop($parts);

  // grab the hostname
  $host = array_pop($parts) . '.' . $tld;

  // have we collected a double TLD?
  if (!empty($parts) && in_array($host, $doubleTlds)) {
   $host = array_pop($parts) . '.' . $host;
  }

  return $host;
 }

 return 'unknown domain';
}

Comments