I've searched to the ends of the internet for an answer on this, and I'm about to come to the logical conclusion that it's impossible. How on earth is one meant to use relative roots when including a file that has other multiple files dependent on it in different directories/levels?
As an example here's a simplified tree of my site:
Main site (PHP reports the main root to be: /Users/Luke/Sites/)
-> index.php
-> directoryfolder - > secondaryindex.php
-> templates -> header.php
-> navigation.php
I.e. if one were to navigate to index.php in Finder, they would see the directory as /Users/Luke/Sites/SiteAlpha/index.php.
Both index.php & directoryfolder/secondaryindex.php includes header.php, which then includes navigation.php. The problem seems to be, whatever I name the include location of navigation.php on header.php, it will only allow one page to correctly display it. I.E.:
If navigation.php is called (via header.php) on index.php, with an include location of ROOT_PATH.'/templates/navigation.php (where ROOT_PATH is equal to dirname(__DIR__
)), it won't display at all. But it will work on secondaryindex.php.
And vice versa too. If navigation.php is called (via header.php) on index.php, with an include location of ROOT_PATH.'/siteAlpha/templates/navigation.php, it will actually work. But then it won't work on secondaryindex.php.
TL;DR, due to the fact that header.php is called by multiple pages on different directory levels, the include to navigation.php has to be simultaneously my first example and my second example.
I've tried using $_SERVER['DOCUMENT_ROOT'], dirname(__DIR__
), __FILE__
, my own defined root constant, to no success whatsoever. I've read and read and read countless articles and SO questions to no help. It just doesn't work.
Can someone care to give me an ELI5 explanation about what I need to do to get it working?
First of all, I'm convinced that an application should only have exactly one entry point. Adapted to your situation, you could include secondayrindex.php in index.php if a specific parameter is set. Similar situation with the templates: build a single template which includes navigation.php and header.php. Then you have to include only the single template. Or use a template engine like smarty which does a lot of work for you (ducking down pls don't hit me, template engine haters)
Back to your case. I see a handful of possible solutions for you:
define('APP_ROOT', __DIR__)
define('APP_ROOT', dirname(__DIR__))
require('navigation.php')
require('templates' . DIRECTORY_SEPARATOR . 'header.php')
require('..' . DIRECTORY_SEPARATOR . 'templates' . DIRECTORY_SEPARATOR . 'header.php')
Btw:
Think of doing sth like this: define('DS', DIRECTORY_SEPARATOR)
- writing DIRECTORY_SEPARATOR
will drive you crazy.
I'm currently in the stage of using absolute paths only while defining a root directory constant at the entry point or a file included into the entry point which defines all necessary constants.
Hope this could help.