Get Root Directory Path of a PHP project

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

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

When I try this code

echo $_SERVER['DOCUMENT_ROOT']

output is

D:/workspace

How can I get the path to RootDirectory of the system (MySystem), without hardcoding the Folder Name?


For PHP >= 5.3.0 try

PHP magic constants.

__DIR__

And make your path relative.

For PHP < 5.3.0 try

dirname(__FILE__)

When you say that

$_SERVER['DOCUMENT_ROOT']

contains this path:

D:/workspace

Then D: is what you are looking for, isn't it? In that case you could explode the string by slashes and return the first one:

$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']);
echo $pathInPieces[0];

This will output the server's root directory.

Update: When you use the constant DIRECTORY_SEPARATOR instead of the hardcoded slash ('/') this code is also working under Windows.

Update 2: The $_SERVER global variable is not always available. On command line (cli) for example. So you should use __DIR__ instead of $_SERVER['DOCUMENT_ROOT']. __DIR__ returns the path of the php file itself.


use the PHP function:

getcwd()

Gets the current working directory.


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