I have this situation:
/
index.php
/init (folder)
init.php (of course inside this file I use require_once for db/function/and whatever you want to put inside)
/layout_parts (folder)
header.php (and others common parts are inside this folder)
/my_space (folder inside layout parts)
my_file.php
another_file.php
/your_space (folder inside layout parts)
your_file.php
another_file.php
/third_space (folder inside layout parts)
third_file.php
another_file.php
For the index I have no problem it all works fine, but if I include header.php
in one of the subfolder files my require_once(init/init.php);
that is on the top of header.php won't work.
(Warning message says no such file in the directory (OF COURSE THE FILE EXIST) and it write down the subfolder directory that is not the path I expected).
I tried echo $SERVER['DOCUMENT_ROOT];
to see the whole path, echo __DIR__;
to see which is the right path to the directory, no way out.
I know is such a dummy question but if some kind heart could help me it would be great. Thanks
The best way to handle this would be to use absolute paths instead of relative ones. When you use relative paths, you have to worry each time about how many levels deep you are and then have that many ../
etc. This is messy and difficult to manage, for eg, if you move a file to a different location, you have to update the includes again, based on where you are now. This is why absolute paths are helpful.
So create something like this:
$appRoot = "/path/to/root/folder/";
This is the path where the index.php file is located. It is the "application root", if you will.
Now, in ANY file where you want to include init.php
add the following line:
include_once($appRoot."init/init.php");
Ideally the $appRoot
should be created in a global config
located in root. If you do not have a structure where a univeral config can be added, it can still be messy and you might need to add absolute paths into individual files (which is not a good idea)