0

I'm currently using the following to get the subdomain of my site

$subdomain = array_shift(explode(".",$_SERVER['HTTP_HOST'])); 

When I use this for http://www.website.com it returns "www" which is expected

However when I use this with http://website.com it returns "website" as the subdomain. How can I make absolute sure that if there is no subdomain as in that example, it returns NULL?

Thanks!

Chris Favaloro
  • 79
  • 1
  • 12
  • what does $_SERVER['SERVER_NAME'] give you ? – Maximus2012 Aug 05 '13 at 13:38
  • Possibly to duplity content http://stackoverflow.com/questions/5292937/php-function-to-get-the-subdomain-of-a-url http://stackoverflow.com/questions/13832626/how-to-get-the-first-subdomain-with-php – Dawlys Aug 05 '13 at 13:45
  • I checked out that post, it's a bit different as I want to return null if the subdomain is not present.. while that returns the domain as the sub. – Chris Favaloro Aug 05 '13 at 14:07

3 Answers3

2

Please, note that in common case you should first apply parse_url to incoming data - and then use [host] key from it. As for your question, you can use something like this:

preg_match('/([^\.]+)\.[^\.]+\.[^\.]+$/', 'www.domain.com', $rgMatches);
//2-nd level check:
//preg_match('/([^\.]+)\.[^\.]+\.[^\.]+$/', 'domain.com', $rgMatches);
$sDomain = count($rgMatches)?$rgMatches[1]:null;

But I'm not sure that it's exactly what you need (since url can contain 4-th domain level e t.c.)

Alma Do
  • 37,009
  • 9
  • 76
  • 105
1

Do this:

function getSubdomain($domain) {
    $expl = explode(".", $domain, -2);
    $sub = "";
    if(count($expl) > 0) {
        foreach($expl as $key => $value) {
            $sub = $sub.".".$value;

        }
        $sub = substr($sub, 1);
    }
    return $sub;
}
$subdomain = getSubdomain($_SERVER['HTTP_HOST']);

Works fine for me. Basicly you need to use the explode limit parameter.
Detail and source: phph.net - explode manual

devdot
  • 178
  • 6
0

If you have other domain, like a .net or .org etc, just change the value accordingly

$site['uri'] = explode(".", str_replace('.com', '', $_SERVER['HTTP_HOST']) );
if( count($site['uri']) >0 ) {
    $site['subdomain'] = $site['uri'][0];
    $site['domain'] = $site['uri'][1];
    }
else  { 
    $site['subdomain'] = null;
    $site['domain'] = $site['uri'][0];
}
//For testing only:
print_r($site);

...or not (for more flexibility):

$site['uri'] = explode(".", $_SERVER['HTTP_HOST'] );
if( count($site['uri']) > 2 ) {
    $site['subdomain'] = $site['uri'][0];
    $site['domain'] = $site['uri'][1];
    }
else  { 
    $site['subdomain'] = null;
    $site['domain'] = $site['uri'][0];
}
//For testing only:
print_r($site);
Omar
  • 11,783
  • 21
  • 84
  • 114