Instead of using $_SERVER['DOCUMENT_ROOT']
, why not declare a constant which always holds the root of your web application?
<?php
define('ABSPATH', dirname(__FILE__));
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:
<?php
require_once('includes/config/abspath.php');
and you have access to ABSPATH
.
In ~/dir/someOtherPage.php
you do the following:
<?php
require_once('../includes/config/abspath.php');
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.