How to get the first subdomain with PHP?

2019-02-19 04:31发布

I have a static domain of dev.example.com with wildcard subdomains like so *.dev.example.com.

I need to detect the name of the current wildcard subdomain. So if I'm browsing sub.dev.example.com how do I get "sub"?

$env_domain = dev.example.com;
$subdomain = array_shift( explode( '.', $_SERVER['HTTP_HOST'] ) ) .'.'. $env_domain;
echo $subdomain;

Currently, this returns dev. I need it to return sub.

I'm thinking the best practice here would be to return the most low-level domain (the first subdomain).

Note that I'm not parsing a URL, but a given domain.

标签: php subdomain
5条回答
趁早两清
2楼-- · 2019-02-19 05:04

I think using parse_url function is much better approach:

getUrlSubdomain($url){
    $urlSegments = parse_url($url);
    $urlHostSegments = explode('.', $urlSegments['host']);

    if(count($urlHostSegments) > 2) {
        return $urlHostSegments[0];
    }
    else{
        return null;
    }
}
查看更多
疯言疯语
3楼-- · 2019-02-19 05:06

This is another simple solution for the question.

echo array_shift((explode(".",$_SERVER['HTTP_HOST'])));
查看更多
我命由我不由天
4楼-- · 2019-02-19 05:11

Here's a little function that'll do the trick. Just stick $_SERVER['HTTP_HOST'] into the function and you should get what you want

function getSubDomain ($domain) {
    $eDom = explode('.', $domain);
    return $eDom[0];
}

echo getSubDomain('sub.dev.example.com'); // echo 'sub' 
查看更多
可以哭但决不认输i
5楼-- · 2019-02-19 05:16
$domain = 'sub.dev.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
print($subdomain);     // prints "sub"
查看更多
成全新的幸福
6楼-- · 2019-02-19 05:24

From PHP 5.3 you can use strstr() with true parameter

echo strstr('sub.dev.example.com', '.', true); //prints sub

Original link

查看更多
登录 后发表回答