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!
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.)
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
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);