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
$pathInPieces = explode('/', $_SERVER['DOCUMENT_ROOT']); echo $pathInPieces[0]; This will output the server's root directory.
The root URL is the section between the colon-slash-slash (://) and the next slash (/), omitting any port number (:portno). That is, if you want to license your server at http://www.somebody.com:1080 the root URL is “www.somebody.com”.
$_SERVER['DOCUMENT_ROOT'] returns. The document root directory under which the current script is executing, as defined in the server's configuration file.
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. .
For future googlers, this also works for me
substr(substr(__FILE__, strlen(realpath($_SERVER['DOCUMENT_ROOT']))), 0, - strlen(basename(__FILE__)));
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With