How can I get the “application root” of my URL from PHP?

后端 未结 6 783
眼角桃花
眼角桃花 2020-12-09 09:06

If my URL is http://www.server.com/myapp/stuff/to/see and my directory structure on disk is htdocs/myapp/*, how can I extract the /myapp

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-09 10:07

    Put the following code in a file located in the root folder of your application and include it on every page load.

    Then, you can simply always do $path = ABSPATH . '/path/to/file.php'; regardless of if your local copy is in a sub-directory folder or not.


    If your application already has a file which is included on every page load, you can simply drop the code above in that file and it will work.

    Just note that you may have to add additional dirname() calls depending on where that file is located. Add one for each directory you pass from the root of your webapp.

    For example, if your webapp is located in /webapp/ and your "global include" is located in /webapp/includes/framework/init.php, then the above code needs to be modified as such:

    define('ABSPATH', dirname(dirname(dirname(__FILE__))));
    

    ie.: 2 additional dirname() calls due to two additional folders from the webapp root (includes/framework)


    Clarification

    The code above is meant to be in one file, and one file only in your web application. That file needs to be included on each page load.

    If you already have a file which is included before any processing (such as a configuration file or other), you may copy and paste that code in that file.

    The number of dirname() calls depends on how deep the file you copied and pasted the code in is relative to the root directory of your web application. For the examples above, assume the root of your web application is represented by ~.

    If you copy-paste my code into ~/abspath.php, then you need one dirname() call.

    If you copy-paste my code into ~/includes/abspath.php, then you need two dirname() calls.

    If you copy-paste my code into ~/includes/config/abspath.php, then you need three dirname() calls. Now let's just say that's its final location.

    In ~/index.php, you do the following:

    and you have access to ABSPATH.

    In ~/dir/someOtherPage.php you do the following:

    and you have access to ABSPATH.

    This is why I'm saying that if you already have a file which is included on each page load, its simpler just to drop the above code in it. Just make sure you modify the amount of dirname() calls accordingly. Again, this code is meant to be in ONLY ONE FILE.


    Then do get the URL path, its a simple matter of removing the DOCUMENT_ROOT FROM ABSPATH:

    $docRoot = rtrim($_SERVER['DOCUMENT_ROOT'], '/');
    define('RELADDR', substr(ABSPATH, strlen($docRoot));
    

提交回复
热议问题