I don’t know why I didn’t think of this solution sooner! I was having this problem on a couple websites I maintain, that I needed to include some additional files, with extra content such as sidebars.
At first, I’d started out with a URL relative to the site root:
<?php include_once "/file.php"; ?>
But…that turns out to be insanely slow, as the php processor makes an HTTP request to download the page rather than loading it directly from the file system, because it treats it as a URL instead of a file system path address.
So then I’d switched the URLs to be relative to the page, so it would load it directly from the file-system. Not so bad in the basic case where everything’s in the same folder:
<?php include_once "./file.php"; ?>
But, when you start including one global file in everything, you can’t just copy and paste the URL from file to file. Somewhere deeper in the site, the include needs to change to include a stack of parent directories to locate the file.
<?php include_once "./../../file.php"; ?>
The other alternative would be to prefix the file with it’s actual location on the file-system, however, with crazy paths like
/home4/mydomain/site1/
that I can’t be bothered to remember off the top of my head, let alone change every time I want to re-use the code on a different domain, that didn’t seem like a good solution.But then, after fixing a few more broken links caused by the author of the new pages copying and pasting a template page from a different directory and forgetting to update those dot-dots, again, I decided to take another look into whether there’s an better way to refer to the file-system without making it super-slow.
And then an insight came to me, perhaps there’s a PHP variable that will give me the path to the site’s root dynamically without all that
/home4/
garbage in the include directly. Aha! Yes, there is, $_SERVER["DOCUMENT_ROOT"]
and Tada! problem solved!So I changed all my includes to look more like:
<?php include_once $_SERVER["DOCUMENT_ROOT"]."/file.php"; ?>
and no more having to fix broken sidebars because the include URL went wrong again. And it can copy and paste between domains cleanly. I don’t know why I didn’t think of this solution sooner, but I’m glad I came up with it!