PHP how to get the base domain/url?

后端 未结 12 2094
渐次进展
渐次进展 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

    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

提交回复
热议问题