Are PHP include paths relative to the file or the calling code?

@Pekka got me there, but just want to share what I learned:

getcwd() returns the directory where the file you started executing resides.

dirname(__FILE__) returns the directory of the file containing the currently executing code.

Using these two functions, you can always build an include path relative to what you need.

e.g., if b.php and c.php share a directory, b.php can include c.php like:

include(dirname(__FILE__).'/c.php');

no matter where b.php was called from.

In fact, this is the preferred way of establishing relative paths, as the extra code frees PHP from having to iterate through the include_path in the attempt to locate the target file.

Sources:

Difference Between getcwd() and dirname(__FILE__) ? Which should I use?

Why you should use dirname(__FILE__)


It's relative to the main script, in this case A.php. Remember that include() just inserts code into the currently running script.

That is, does it matter which file the include is called from

No.

If you want to make it matter, and do an include relative to B.php, use the __FILE__ constant (or __DIR__ since PHP 5.2 IIRC) which will always point to the literal current file that the line of code is located in.

include(dirname(__FILE__)."/C.PHP");