I have a configuration file. This is not a stand-alone file. I will be including this file at the top of the pages that I want to use in, using require(). I want to dynamically get the complete absolute url path to this configuration file, regardless of it’s location and store it as a constant within itself. For example:
Physical Location: (root dir)/my_folder/configuration.php
Need URL as: http://www.mydomain.com/my_folder/configuration.php
Physical Location: (root dir)/demos/my_folder/configuration.php
Need URL as: http://www.mydomain.com/demos/my_folder/configuration.php
Physical Location: (root dir)/demos/site1/my_folder/configuration.php
Need URL as: http://www.mydomain.com/demos/site1/my_folder/configuration.php
Physical Location: (root dir)/demos/site2/my_folder/configuration.php
Need URL as: http://www.mydomain.com/demos/site2/my_folder/configuration.php
Simple so far? Here’s what really needed and makes it complicated (IMO). Consider this:
Config file located at: http://www.mydomain.com/demos/site2/my_folder/configuration.php
Have nested folders: http://www.mydomain.com/demos/site2/1/2/3/index.php
When I access the index.php file in the “3” sub-folder by following the URL above, I need the path to configuration file as http://www.mydomain.com/demos/site2/my_folder/configuration.php and not as http://www.mydomain.com/demos/site2/1/2/3/my_folder/configuration.php
How can I achieve the above?
If you can rely on the value of
$_SERVER[ 'DOCUMENT_ROOT' ], then insideconfiguration.php:If it fits your use case, you can make it more dynamic using
$_SERVER[ 'HTTP_HOST' ];DOCUMENT_ROOT
I’ve used
DOCUMENT_ROOTliberally in my development, as it’s often the only dynamic variable available for constructing certain self-referential paths. There’s a looong running Apache bug ticket (#26052) about howDOCUMENT_ROOTis poorly handled, particularly that Apache wouldn’t allow you to set the value withRewriteRuleand didn’t set it to a sensible value when using mod_vhost_alias. The discussion goes on over a period of 7-8 years as people presumably from the Apache project resist changing the behavior, until they finally came around and made a change this year in 2.4.1. (I looked into this previously, but I forget now what the exact changes were, and how satisfying they are.)If you look at the comments on the ticket you’ll see people resisting changes to the behavior with comments like:
So I suggest reading the comments on that ticket to see what people are saying the caveats of using it are. I’ve used it with a lot of success and don’t know of a better way to achieve the same things in the same situations that
DOCUMENT_ROOTis available and provides the necessary data.