0

Is there any predefined method in PHP to get sub-domain from url if any?

url pattern may be:

http://www.sd.domain.com
http://domain.com
http://sd.domain.com
http://domain.com

where sd stands for sub-doamin.

Now method must return different values for every case:

case 1 -> return sd

case 2 -> return false or empty

case 3 -> return sd

case 4 -> return false or empty

I found some good links

PHP function to get the subdomain of a URL

Get subdomain from url?

but not specifically apply on my cases.

Any help will be most appreciable.

Thanks

Community
  • 1
  • 1
PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149

3 Answers3

0

Okay, here I create a script :)

$url = $_SERVER['HTTP_HOST'];
$host = explode('.', $url);
if( !empty($host[0]) && $host[0] != 'www' && $host[0] != 'localhost' ){
    $domain = $host[0];
}else{
    $domain = 'home';
}
PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149
0

So, there are several possibilities...

First, regular expressions of course:

(http://)?(www\.)?([^\.]*?)\.?([^\.]+)\.([^\.]+)

The entry in the third parenthesis will be your subdomain. Of course, if your url would be https:// or www2 (seen it all...) the regex would break. So this is just a first draft to start working with.

My second idea is, just as yours, explodeing the url. I thought of something like this:

function getSubdomain($url) {
    $parts = explode('.', str_replace('http://', '', $url));
    if(count($parts) >= 3) {
        return $parts[count($parts) - 3];
    }
    return null;
}

My idea behind this function was, that if an url is splitted by . the subdomain will almost always be the third last entry in the resulting array. The protocol has to be stripped first (see case 3). Of course, this certainly can be done more elegant.

I hope I could give you some ideas.

Joshua
  • 2,932
  • 2
  • 24
  • 40
0

Try this.

[update] We have a constant defined _SITE_ADDRESS such as www.mysite.com you could use a literal for this.

It works well in our system for what seems like that exact purpose.

public static function getSubDomain()
{
    if($_SERVER["SERVER_NAME"] == str_ireplace('http://','',_SITE_ADDRESS)) return ''; //base domain
    $host = str_ireplace(array("www.", _SITE_ADDRESS), "", strtolower(trim($_SERVER["HTTP_HOST"])));
    $sub =  preg_replace('/\..*/', '', $host);
    if($sub == $host) return ''; //this is likely an ip address
    return $sub;
}

There is an external note on that function but no link, So sorry to any original developer who's code this is based on.

Gavin
  • 2,153
  • 2
  • 25
  • 35