PHP how to get the base domain/url?

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


        
12条回答
  •  甜味超标
    2020-12-04 19:48

    /**
     * Suppose, you are browsing in your localhost 
     * http://localhost/myproject/index.php?id=8
     */
    function getBaseUrl() 
    {
        // output: /myproject/index.php
        $currentPath = $_SERVER['PHP_SELF']; 
    
        // output: Array ( [dirname] => /myproject [basename] => index.php [extension] => php [filename] => index ) 
        $pathInfo = pathinfo($currentPath); 
    
        // output: localhost
        $hostName = $_SERVER['HTTP_HOST']; 
    
        // output: http://
        $protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';
    
        // return: http://localhost/myproject/
        return $protocol.'://'.$hostName.$pathInfo['dirname']."/";
    }
    

提交回复
热议问题