How to require PHP files relatively (at different directory levels)?

PhpRelative Path

Php Problem Overview


I have the following file structure:

rootDIR
dir1
subdir1
file0.php
file1.php
dir2
file2.php
file3.php
file4.php

file1.php requires file3.php and file4.php from dir2 like this :

require('../../dir2/file3.php')

file2.php requires file1.php like this:

require('../dir1/subdir1/file1.php')

But then require in file1.php fails to open file3.php and file4.php ( maybe due to the path relativeness)

However, what is the reason and what can I do for file2.php so file1.php properly require file3.php and file4.php?

Php Solutions


Solution 1 - Php

For relative paths you can use __DIR__ directly rather than dirname(__FILE__) (as long as you are using PHP 5.3.0 and above):

require(__DIR__.'/../../dir2/file3.php');

Remember to add the additional forward slash at the beginning of the path within quotes.

See:

Solution 2 - Php

Try adding dirname(__FILE__) before the path, like:

require(dirname(__FILE__).'/../../dir2/file3.php');

It should include the file starting from the root directory

Solution 3 - Php

A viable recommendation is to avoid "../../" relative paths in your php web apps. It's hard to read and terrible for maintenance.

  1. As you can attest. It makes it extremely difficult to know what you are pointing to.

  2. If you need to change the folder level of your application, or parts of it. It's completely prone to errors, and will likely break something that is horrible to debug.

Instead, a preferred pattern would be to define a few constants in your bootstrap file for your main path(s) and then use:

require(MY_DIR.'/dir1/dir2/file3.php');

Moving your app from there, is as easy as replacing your MY_DIR constants in one single file.

If you must keep it relative. At a minimum, construct an absolute path based on a relative path reference, like the accepted response suggest. However also strongly keep in mind the importance of naming your ../ anonymous intermediate paths, as a means to remove confusion or ambiguity.

Solution 4 - Php

You can always use the $_SERVER['DOCUMENT_ROOT'] as a valid starting point, as well, rather than resorting to a relative path. Just another option.

require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');

Solution 5 - Php

I think your cwd is dir2. Try :

require("file3.php");
require("file4.php");

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBoris D. TeoharovView Question on Stackoverflow
Solution 1 - PhpSharpCView Answer on Stackoverflow
Solution 2 - PhpBaronthView Answer on Stackoverflow
Solution 3 - PhphexalysView Answer on Stackoverflow
Solution 4 - PhpGrantView Answer on Stackoverflow
Solution 5 - PhpAmit KriplaniView Answer on Stackoverflow