Search code examples
phpparsingurlsubdomain

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];

Solution

  • 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);