Reputation: 33956
I rely heavily in $_SERVER["DOCUMENT_ROOT"]
to get absolute paths. However this doesn't work for sites which URLs don't point to the root.
I have sites stored in folders such as:
all directly inside the root. Is there a way to get the path in the server where the current site root is?
It should return:
/var/chroot/home/content/02/6945202/html/site1 // If the site is stored in folder 'site1'
/var/chroot/home/content/02/6945202/html // If the site is stored in the root
Upvotes: 11
Views: 45980
Reputation: 2035
use the following method to get the absolute root url from your server settings
str_replace($_SERVER['DOCUMENT_ROOT']."/",$_SERVER['PHPRC'],$_SERVER['REAL_DOCUMENT_ROOT'])
or use the getcwd(). it gets the current working directory of your application
Upvotes: 0
Reputation: 8312
Just use getcwd()
for the current absolute server path of the folder the current script is in.
You can define a constant at the top of your website so that the rest of the website can rely on that path.
define('MY_SERVER_PATH', getcwd());
Upvotes: 1
Reputation: 11824
For future googlers, this also works for me
substr(substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))), 0, - strlen(basename(__FILE__)));
Upvotes: 1
Reputation: 173562
You can simply append dirname($_SERVER['SCRIPT_NAME'])
to $_SERVER['DOCUMENT_ROOT']
.
Update
The website seems to be directory "mounted" on that folder, so SCRIPT_NAME
will obviously be /
.
So, to make this work you have to use either __DIR__
or dirname(__FILE__)
to find out where your script is located in the file system.
Update 2
There's no single index.php
controller for the whole site, so that won't work either.
The following expression does a string "subtraction" to find the common path. You have a known prefix (document root), an unknown (the root folder) and a known suffix (the script path), so to find the first two, you take the full absolute path (__FILE__
) and subtract the known suffix:
substr(__FILE__, 0, -strlen($_SERVER['SCRIPT_NAME']));
If included files need this value, you must store this in a constant first before including the dependent scripts. .
Upvotes: 15