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

Boris D. Teoharov picture Boris D. Teoharov · Oct 18, 2012 · Viewed 44.1k times · Source

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?

Answer

Baronth picture Baronth · Oct 18, 2012

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

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

It should include the file starting from the root directory