Get Root Directory Path of a PHP project

后端 未结 9 813
醉酒成梦
醉酒成梦 2020-12-04 11:46

I have this folder structure in my PHP project. (this is as shown in eclips)

-MySystem
    +Code
    +Data_Access
    -Public_HTML
        +css
        +js
         


        
相关标签:
9条回答
  • 2020-12-04 12:07

    you can try: $_SERVER['PATH_TRANSLATED']

    quote:

    Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache.
    This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO

    source: php.net/manual

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

    You could also use realpath.

    realpath(".") returns your document root.

    You can call realpath with your specific path. Note that it will NOT work if the target folder or file does not exist. In such case it will return false, which could be useful for testing if a file exists.

    In my case I needed to specify a path for a new file to be written to disk, and the solution was to append the path relative to document root:

    $filepath = realpath(".") . "/path/to/newfile.txt";

    Hope this helps anyone.

    0 讨论(0)
  • 2020-12-04 12:18

    I want to point to the way Wordpress handles this:

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

    As Wordpress is very heavy used all over the web and also works fine locally I have much trust in this method. You can find this definition on the bottom of your wordpress wp-config.php file

    0 讨论(0)
  • 2020-12-04 12:22

    For PHP >= 5.3.0 try

    PHP magic constants.

    __DIR__
    

    And make your path relative.

    For PHP < 5.3.0 try

    dirname(__FILE__)
    
    0 讨论(0)
  • 2020-12-04 12:22
    echo $pathInPieces = explode(DIRECTORY_SEPARATOR , __FILE__);
    echo $pathInPieces[0].DIRECTORY_SEPARATOR;
    
    0 讨论(0)
  • 2020-12-04 12:26

    use the PHP function:

    getcwd()

    Gets the current working directory.

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