问题
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..
回答1:
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.
require_once __DIR__ . '/../FolderB2/PageB21.php';
You can also make use of realpath().
回答2:
You can add the absolute path to the files
require_once('/home/my_host_account/www/FolderB2/PageB21.php');
Please verify if this is working.
回答3:
You can also create soft-links in each directory referring to your original. But this is a workaround that should be used only if all other methods fail.
来源:https://stackoverflow.com/questions/11840317/make-path-accessible-at-various-level-of-folder-on-php