PHP how to get the base domain/url?

后端 未结 12 2089
渐次进展
渐次进展 2020-12-04 18:43
function url(){
    if(isset($_SERVER[\'HTTPS\'])){
        $protocol = ($_SERVER[\'HTTPS\'] && $_SERVER[\'HTTPS\'] != \"off\") ? \"https\" : \"http\";
    }         


        
相关标签:
12条回答
  • 2020-12-04 19:22

    Shortest solution:

    $domain = parse_url('http://google.com', PHP_URL_HOST);
    
    0 讨论(0)
  • 2020-12-04 19:22

    Step-1

    First trim the trailing backslash (/) from the URL. For example, If the URL is http://www.google.com/ then the resultant URL will be http://www.google.com

    $url= trim($url, '/');
    

    Step-2

    If scheme not included in the URL, then prepend it. So for example if the URL is www.google.com then the resultant URL will be http://www.google.com

    if (!preg_match('#^http(s)?://#', $url)) {
        $url = 'http://' . $url;
    }
    

    Step-3

    Get the parts of the URL.

    $urlParts = parse_url($url);
    

    Step-4

    Now remove www. from the URL

    $domain = preg_replace('/^www\./', '', $urlParts['host']);
    

    Your final domain without http and www is now stored in $domain variable.

    Examples:

    http://www.google.com => google.com

    https://www.google.com => google.com

    www.google.com => google.com

    http://google.com => google.com

    0 讨论(0)
  • 2020-12-04 19:25

    This works fine if you want the http protocol also since it could be http or https. $domainURL = $_SERVER['REQUEST_SCHEME']."://".$_SERVER['SERVER_NAME'];

    0 讨论(0)
  • 2020-12-04 19:30

    Use SERVER_NAME.

    echo $_SERVER['SERVER_NAME']; //Outputs www.example.com
    
    0 讨论(0)
  • 2020-12-04 19:30

    You could use PHP's parse_url() function

    function url($url) {
      $result = parse_url($url);
      return $result['scheme']."://".$result['host'];
    }
    
    0 讨论(0)
  • 2020-12-04 19:30

    Please try this:

    $uri = $_SERVER['REQUEST_URI']; // $uri == example.com/sub
    $exploded_uri = explode('/', $uri); //$exploded_uri == array('example.com','sub')
    $domain_name = $exploded_uri[1]; //$domain_name = 'example.com'
    

    I hope this will help you.

    0 讨论(0)
提交回复
热议问题