Building a dynamic path to the document root for the include function
I like to build modular sites, always have, always will. We
used to use frames to set up navigation links and headers and
footers but there were so many issues with doing that. Then
along came Server Side Includes (SSI) which allowed people to
include those files at runtime into the page. Life was good.
PHP has this functionality, but one of the seriously frustrating
things about it is the lack of being able to include files
relative to the website root directory. This means you have to
use the ../ syntax to back up a folder, sometimes
multiple times, and then drill down through another folder.
For explanation purposes, here's what I mean:
The folder where your website pages reside for Site1 on the
In that folder is your index page some sub-folders containing
groups of related pages, and also an includes folder.
The includes/site.css is used for every page on the website,
and includes/db_connect.php is used on multiple pages throughout
the site where you need database connections.
Using the page C:\Apache\htdocs\site1\folder2\subfolder2-1\my_database_page.php,
and wanting to include the includes/db_connect.php page, you'd
have to do it as follows:
Now, that's no big deal to do, but what if you decide to move
the my_database_page.php into folder3? You'd have to remember
to take out one set of ../ in your include statements.
Well, after much searching the PHP website, I decided to write
my own function to dynamically put in the right number of ../
so that I could move the pages anywhere without having to fix
them, and this is what I ended up with.
$levels = substr_count($_SERVER['PHP_SELF'],"/");
for ($i=0; $i < $levels - 1; $i++)
$relativeDir .= "../";