How can I find an application's base url?

后端 未结 11 1391
南方客
南方客 2020-12-16 01:35

I\'d like to find the base url of my application, so I can automatically reference other files in my application tree...

So given a file config.php in the base of my

相关标签:
11条回答
  • 2020-12-16 02:01

    I use the following in a homebrew framework... Put this in a file in the root folder of your application and simply include it.

    define('ABSPATH', str_replace('\\', '/', dirname(__FILE__)) . '/');
    
    $tempPath1 = explode('/', str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'])));
    $tempPath2 = explode('/', substr(ABSPATH, 0, -1));
    $tempPath3 = explode('/', str_replace('\\', '/', dirname($_SERVER['PHP_SELF'])));
    
    for ($i = count($tempPath2); $i < count($tempPath1); $i++)
        array_pop ($tempPath3);
    
    $urladdr = $_SERVER['HTTP_HOST'] . implode('/', $tempPath3);
    
    if ($urladdr{strlen($urladdr) - 1}== '/')
        define('URLADDR', 'http://' . $urladdr);
    else
        define('URLADDR', 'http://' . $urladdr . '/');
    
    unset($tempPath1, $tempPath2, $tempPath3, $urladdr);
    

    The above code defines two constants. ABSPATH contains the absolute path to the root of the application (local file system) while URLADDR contains the fully qualified URL of the application. It does work in mod_rewrite situations.

    0 讨论(0)
  • 2020-12-16 02:01

    url root of the application can be found by

    $protocol = (strstr('https',$_SERVER['SERVER_PROTOCOL']) === false)?'http':'https';
    $url = $protocol.'://'.$_SERVER['SERVER_NAME'].dirname($_SERVER['REQUEST_URI']);
    

    this code will return url path of any application whether be online or on offline server.

    I've not made proper check for proper '/'. Please modify it for slashes.

    this file should be placed in root.

    example : if application url :

    http://localhost/test/test/test.php
    

    then this code will return

    http://localhost/test/test
    

    Thanks

    0 讨论(0)
  • 2020-12-16 02:02

    Put this in your config.php (which is in your app's root dir):

    $approot = substr(dirname(__FILE__),strlen($_SERVER['DOCUMENT_ROOT']));
    

    I think that'll do it.

    0 讨论(0)
  • 2020-12-16 02:03

    If you want the path on the filesystem you can use $_SERVER['DOCUMENT_ROOT']
    If you just want the path of the file that appears in the URL after the domain use $_SERVER['REQUEST_URI']

    0 讨论(0)
  • 2020-12-16 02:12

    This works like a charm for me, anywhere I deploy, with or without rewrite rules:

    $baseDir = 'http://'.$_SERVER['HTTP_HOST'].(dirname($_SERVER['SCRIPT_NAME']) != '/' ? dirname($_SERVER["SCRIPT_NAME"]).'/' : '/');

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