I have this folder and file structure:
- public_html (folder)
- index.php (file)
- resources (folder)
- configs (folder)
- main_config.php (file)
- render_template.php (file) - (this file is at the same level as configs folder, inside resources folder)
- configs (folder)
In index.php I call:
require_once("../resources/render_template.php");
In render_template.php I call:
require_once("configs/main_config.php");
Or: (both work)
require_once("../resources/configs/main_config.php");
My questions:
Why does the
require_once("configs/main_config.php")
work? Shouldn't the path now need to be relative to the index.php because the render_template.php file is included in the index.php which means need to add ../resources/ to leave the public_html folder?
If the first way is correct, why does
require_once("../resources/configs/main_config.php");
then work?
My Answer:
The reason why require_once("configs/main_config.php") works in render_template.php is because PHP resolves the path relative to the current working directory, which is the directory of the script that is currently being executed. In this case, when render_template.php is included in index.php, the current working directory is still the directory of index.php, so the path "configs/main_config.php" is resolved correctly.
On the other hand, require_once("../resources/configs/main_config.php") also works because the "../" at the beginning of the path tells PHP to go up one level in the directory structure before looking for the resources folder. So in this case, PHP goes up one level from the directory of index.php (which is public_html) and then looks for the resources folder and the configs folder inside it.
Both ways of including the file work because PHP resolves the paths relative to the current working directory, and the "../" notation allows you to navigate up and down the directory structure as needed.
Rate this post
3 of 5 based on 8601 votesComments