Assume that I have a folder with some folders and pages on it:
- FolderA
- PageA1.php
- FolderB
- FolderB1
- PageB11.php
- FolderB2
- PageB21.php
- PageB1.php
- FolderB1
- FolderC
- PageC1.php
On PageB11, I have:
require_once 'FolderB2/PageB21.php';
While calling PageB11 on PageB1:
require_once 'FolderB1/PageB11.php';
It’s work fine. But now the problem is, while on PageB11 also have a function that call the page itself (PageB11), then the error showed:
Warning: require_once(FolderB2/PageB21.php): failed to open stream: No such file or directory in Path\FolderB\FolderB1\PageB11.php on line X
When I changed the require_once line on PageB11 become: require_once '../FolderB2/PageB21.php';, it’s work!
What I wanna do is, how to make all of it accessible at various level of folder? Is is possible to do that? Thanks..
As stated, the best way of handling such situations, is to refer to each file by its absolute path. This is the path from the root of the filesystem, unlike a relative path which is given relative by the current file.
In PHP you have a magical constant
__DIR__, which gives the absolute path of the current file. Prepend every include/require with that, and you’ll never see that problem again.You can also make use of
realpath().