Writing code in PHP, how can I ensure the require_once path of a script is translated correctly regardless of where the calling script is?
Assuming a folder structure of:
ROOT
{subfolder
{subfolderX
In my “script A” which is in a subfolder called scripts it requires another script in another subfolder called “script B,” so my require looks like
require_once("../subfolderX/script B");
This all works okay. But if I call script A from another script which is say up a level such as:
require_once("subfolder/script A");
The call to script B doesn’t work becasue it’s now relative to the new calling script.
What is the correct technique here to ensure the path stays relative to the calling script?
Use the PHP magic constant
__DIR__, which will point to the directory that the script resides in. In other words, do this:Instead of this: