PHP how to get the base domain/url?

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


        
12条回答
  •  天涯浪人
    2020-12-04 19:31

    Use parse_url() like this:

    function url(){
        if(isset($_SERVER['HTTPS'])){
            $protocol = ($_SERVER['HTTPS'] && $_SERVER['HTTPS'] != "off") ? "https" : "http";
        }
        else{
            $protocol = 'http';
        }
        return $protocol . "://" . parse_url($_SERVER['REQUEST_URI'], PHP_URL_HOST);
    }
    

    Here is another shorter option:

    function url(){
        $pu = parse_url($_SERVER['REQUEST_URI']);
        return $pu["scheme"] . "://" . $pu["host"];
    }
    

提交回复
热议问题