Shafizadeh
Shafizadeh

Reputation: 10340

How to get the subdomain of a URL using PHP?

I have some URLs like these:

1.  https://www.example.com/classname/method/arg      // {nothing}
2.  http://www.example.com/classname/method/arg       // {nothing}
3.  https://example.com/classname/method/arg          // {nothing}
4.  http://example.com/classname/method/arg           // {nothing}
5.  www.example.com/classname/method/arg              // {nothing}
6.  example.com/classname/method/arg                  // {nothing}
7.  sub.example.com/classname/method/arg              // sub
8.  www.sub.example.com/classname/method/arg          // sub
9.  http://sub.example.com/classname/method/arg       // sub
10. https://sub.example.com/classname/method/arg      // sub
11. http://www.sub.example.com/classname/method/arg   // sub
12. https://www.sub.example.com/classname/method/arg  // sub

// $url ^                                             // What I want ^

Now, as you see I want to get sobdomain of those URLs. How?


I have two approaches, but none of them doesn't work for all URLs as well:

First: (this just work for 7)

echo array_shift((explode(".",$url)));

Second: (It's better a bit)

$parsedUrl = parse_url($url);
$host = explode('.', $parsedUrl['host']);
echo $host[0];

Upvotes: 1

Views: 8068

Answers (3)

NinjaKC
NinjaKC

Reputation: 841

I am going to leave this here...

Using @TwoStraws' idea, I created a function which will provide the Sub Domain, Base Domain, and TLD Domain parts from a given URL, using data.iana.org's up to date TLD list.

function GetDomainParts($URL,$TLDs_List = 'http://data.iana.org/TLD/tlds-alpha-by-domain.txt') {
    // Get a list of all top level domains
    $TLDs = explode(PHP_EOL,file_get_contents($TLDs_List));
    unset($TLDs[0]); array_values($TLDs);

    // And since that list has all the country codes too, lets assume all 2 letter domains are country codes, and get that list too
    $CC_TLDs = [];
    foreach($TLDs as $TLD) {
        if(strlen($TLD) == 2) {
            $CC_TLDs[] = $TLD;
        }
    }

    // Now lets take our URL and remove some things
    $ParsedUrl = parse_url($URL);
    $Host = explode('.', $ParsedUrl['host']);

    // If we cant find it, we return false...
    $BaseDomain = false;
    $TLDDomain = false;

    // And look at the last 2 items in the Host array, these will be our TLD's (possibly)
    $N_Minus_1 = strtoupper(isset($Host[count($Host)-1])?$Host[count($Host)-1]:null);
    $N_Minus_2 = strtoupper(isset($Host[count($Host)-2])?$Host[count($Host)-2]:null);

    // This has a potential of being our base domain, but may not be there
    $N_Minus_3 = strtoupper(isset($Host[count($Host)-3])?$Host[count($Host)-3]:null);


    // We first check our N Minus 1 against our list of Country Code TLDs
    if(in_array($N_Minus_1,$CC_TLDs)) {
        // If N Minus 1 is in the Country Code, We can check our N Minus 2 and see if it is in the TLDs array
        if(in_array($N_Minus_2,$TLDs)) {
            // If N Minus 2 is in the list of TLDs, we make the assumption that this is part of the TLD, making N Minus 3 our Base Domain
            $BaseDomain = $N_Minus_3;
            $TLDDomain = $N_Minus_2.'.'.$N_Minus_1;

            // We unset the parts that are used, the rest is our sub domain
            unset($Host[count($Host)-1]);
            unset($Host[count($Host)-1]);
            unset($Host[count($Host)-1]);
            $SubDomain = implode('.',$Host);
        } else {
            // If N Minus 2 is NOT in the list of TLDs, we make the assumption that this is our Base Domain
            $BaseDomain = $N_Minus_2;
            $TLDDomain = $N_Minus_1;

            // We unset the parts that are used, the rest is our sub domain
            unset($Host[count($Host)-1]);
            unset($Host[count($Host)-1]);
            $SubDomain = implode('.',$Host);
        }
    } else {
        // If N Minus 1 is NOT in the Country Codes, we can assume it is the TLD, lets check it against the TLDs to make sure
        if(in_array($N_Minus_1,$TLDs)) {
            // If N Minus 1 Is in our List of TLDs, we can assume we found our TLD, so N Minus 2 must be our Base Domain
            $BaseDomain = $N_Minus_2;
            $TLDDomain = $N_Minus_1;

            // We unset the parts that are used, the rest is our sub domain
            unset($Host[count($Host)-1]);
            unset($Host[count($Host)-1]);
            $SubDomain = implode('.',$Host);
        } else {
            // If N Minus 1 is NOT in our list of TLDs it is either a new TLD unheard of by iana.org, or does not exist, lets make the assumption that it is the tld
            $BaseDomain = $N_Minus_2;
            $TLDDomain = $N_Minus_1;

            // We unset the parts that are used, the rest is our sub domain
            unset($Host[count($Host)-1]);
            unset($Host[count($Host)-1]);
            $SubDomain = implode('.',$Host);

            // Not sure if it is needed, but at this point we can swap the checks, checking minus 2 as the country code and minus 1 as the TLD, 
            // but I am not sure this is ever a real world scenerio, and am unable to find any proof to support this theory
        }

    }

    // Return our URL Parts ( DISCLAIMER: Note that this will not solve every URL, such as WWW.AFAMILYCOMPANY.CO, 
    // because both AFAMILYCOMPANY and CO are TLDs one being a TLD and the other being a Country Code, Leaving "WWW" as the Base Domain.
    // I use this functionality to auto-populate a user changeable setting, just in case my assumption is wrong the user can fix it.
    // One should not assume this will work 100% of the time! )
    return [strtolower($SubDomain),strtolower($BaseDomain),strtolower($TLDDomain)];
}

PLEASE READ THE DISCLAIMER...

Note that this will not solve every URL, such as WWW.AFAMILYCOMPANY.CO, because both AFAMILYCOMPANY and CO are TLDs one being a TLD and the other being a Country Code, Leaving "WWW" as the Base Domain. I use this functionality to auto-populate a user changeable setting, just in case my assumption is wrong the user can fix it. One should not assume this will work 100% of the time!

Further note that, http://whois.domaintools.com/afamilycompany.co is listed as a "Restricted and Reserved Names" domain. If the internet is doing things right, then these type of domains should never be in production anyway, and therefor this function is safe.

A simple way to check if this functionality will work on your domain(s) for sure, is to go to http://data.iana.org/TLD/tlds-alpha-by-domain.txt press Ctrl+F and check if the domain is in the list, if it is, this function will fail, if it is not, this function will work 100% of the time. I realize this is only a step in the right direction, so if anyone else can add onto the idea let me know.

Upvotes: 1

TheBosti
TheBosti

Reputation: 1425

Uses the parse_url.

$url = 'http://sub.example.com/classname/method/arg';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomain = $host[0];
echo $subdomain;

For multiple subdomains you should do like this

$url = 'http://en.sub.example.com/classname/method/arg';

$parsedUrl = parse_url($url);

$host = explode('.', $parsedUrl['host']);

$subdomains = array_slice($host, 0, count($host) - 2 );
print_r($subdomains);

Upvotes: 2

TwoStraws
TwoStraws

Reputation: 13127

You're on the right track using explode(), but you should probably also use the parse_url() function to get the domain from the URL: see here for docs. TL;DR: Give it a URL as its only parameter, and get back an array of all the parts of the URL broken up individually.

That being said, a bigger problem is how you distinguish between subdomain.somesite.com and somesite.co.uk - the first one clearly has a subdomain, but the second one does not. I'm afraid I have no smart solutions to offer for that other than comparing against a list of top-level domains.

Upvotes: 0

Related Questions