【问题标题】:How to get the first subdomain with PHP?如何使用 PHP 获取第一个子域?
【发布时间】:2012-12-12 04:10:27
【问题描述】:

我有一个静态域 dev.example.com 和通配符子域,例如 *.dev.example.com

我需要检测当前通配符子域的名称。那么,如果我正在浏览sub.dev.example.com,我如何获得“sub”?

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

目前,这将返回 dev。我需要它返回sub

我认为这里的最佳做法是返回最低级别的域(第一个子域)。

请注意,我解析的不是 URL,而是给定的域。

【问题讨论】:

    标签: php subdomain


    【解决方案1】:
    $domain = 'sub.dev.example.com';
    $tmp = explode('.', $domain);
    $subdomain = current($tmp);
    print($subdomain);     // prints "sub"
    

    【讨论】:

      【解决方案2】:

      这是该问题的另一个简单解决方案。

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

      【讨论】:

        【解决方案3】:

        我认为使用parse_url 函数是更好的方法:

        getUrlSubdomain($url){
            $urlSegments = parse_url($url);
            $urlHostSegments = explode('.', $urlSegments['host']);
        
            if(count($urlHostSegments) > 2) {
                return $urlHostSegments[0];
            }
            else{
                return null;
            }
        }
        

        【讨论】:

          【解决方案4】:

          这里有一个小函数可以解决问题。 只需将 $_SERVER['HTTP_HOST'] 粘贴到函数中,您就应该得到您想要的

          function getSubDomain ($domain) {
              $eDom = explode('.', $domain);
              return $eDom[0];
          }
          
          echo getSubDomain('sub.dev.example.com'); // echo 'sub' 
          

          【讨论】:

            【解决方案5】:

            从 PHP 5.3 开始,您可以使用带有 true 参数的 strstr()

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

            Original link

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-01-29
              • 2022-01-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-01-19
              • 1970-01-01
              相关资源
              最近更新 更多