47
votes

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?

5

5 Answers

61
votes

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:

55
votes

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

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

It should include the file starting from the root directory

5
votes

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.

1
votes

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');
-2
votes

I think your cwd is dir2. Try :

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