2

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?

2 Answers 2

1

Use the PHP magic constant __DIR__, which will point to the directory that the script resides in. In other words, do this:

require_once __DIR__ . '/../subfolderX/script B';

Instead of this:

require_once '../subfolderX/script B';
Sign up to request clarification or add additional context in comments.

1 Comment

Great answer - thank you. ANother snippet for the memory bank. I needed to add a str replace to make the forward slashes backslashes from the DIR constant but all good and working. Thanks
1

One is you work with a constant in your hole project ..

require_once(ROOT."subfolder/script A");

Second is to put your root director to include_path in your php.ini and make all paths relative to this root directory

2 Comments

Thanks for this. I thought setting constants could be problematic if your not too careful. I went for the DIR method above as appeared to be more transportable? maybe??
I like this version more because the path to the libs are the same in every file .. disadvantage is that the IDE support for clicking the included file to change to it works not so good in this version ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.