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

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:

  • PHP - with require_once/include/require, the path is relative to what?
  • PHP - Relative paths "require"

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

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

It should include the file starting from the root directory


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.