How do I get the root url of the site?

前端 未结 5 1512
时光说笑
时光说笑 2020-12-05 13:20

Might be a trivial question, but I am looking for a way to say get the root of a site url, for example: http://localhost/some/folder/containing/something/here/or/there

5条回答
  •  孤街浪徒
    2020-12-05 14:10

    This PHP function returns the real URL of a full path.

    function pathUrl($dir = __DIR__){
    
        $root = "";
        $dir = str_replace('\\', '/', realpath($dir));
    
        //HTTPS or HTTP
        $root .= !empty($_SERVER['HTTPS']) ? 'https' : 'http';
    
        //HOST
        $root .= '://' . $_SERVER['HTTP_HOST'];
    
        //ALIAS
        if(!empty($_SERVER['CONTEXT_PREFIX'])) {
            $root .= $_SERVER['CONTEXT_PREFIX'];
            $root .= substr($dir, strlen($_SERVER[ 'CONTEXT_DOCUMENT_ROOT' ]));
        } else {
            $root .= substr($dir, strlen($_SERVER[ 'DOCUMENT_ROOT' ]));
        }
    
        $root .= '/';
    
        return $root;
    }
    

    Call of pathUrl in this file : http://example.com/shop/index.php

    #index.php
    
    echo pathUrl();
    //http://example.com/shop/
    

    Work with alias : http://example.com/alias-name/shop/index.php

    #index.php
    
    echo pathUrl();
    //http://example.com/alias-name/shop/
    

    For sub directory : http://example.com/alias-name/shop/inc/config.php

    #config.php
    
    echo pathUrl(__DIR__ . '/../');
    //http://example.com/alias-name/shop/
    

提交回复
热议问题