Are PHP include paths relative to the file or the calling code?
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");
@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__)
-
If include path doesn't start with
./
or../
, e.g.:include 'C.php'; // precedence: include_path (which include '.' at first), // then path of current `.php` file (i.e. `B.php`), then `.`.
-
If include path starts with
./
or../
, e.g.:include './C.php'; // relative to '.' include '../C.php'; // also relative to '.'
The .
or ..
above is relative to getcwd()
, which defaults to the path of the entry .php
file (i.e. A.php
).
Tested on PHP 5.4.3 (Build Date : May 8 2012 00:47:34).
(Also note that chdir()
can change the output of getcwd()
.)