Php require() - Realtive paths
Here's sort of a silly question. When File A does an include() of file B, and file B does an include of file C, and all the the paths are relative开发者_Go百科, are the 'child' references relative to their own path, or to the 'master' file (file A) in which they're included?
for example:
directory structure
Root
header.html (File B)
/images / logo.png (File C)
/site / index.php (File A)
index.php contains: include('../header.html');
header.html contains: include('images/logo.png');
Will this work? Or since index.php is the 'master' file, will it try to look for 'images' within the 'sites' folder?
They are always relative to the "master" file. Included files are treated as "injections" of source code into the main script, so they behave as if they were inside the main script.
To address something relative to the actual current file, use the __FILE__
and __DIR__
constants that always point to the file they're in.
The paths are relative to the working directory. The initial working directory is the directory that contains the PHP file that was executed directly in response to the HTTP request (i.e. what you called master file.).
An include
does not change the working directory, but it can be changed manually by calling chdir. However I advice against changing the working directory solely for the sake of an include
.
Better use set_include_path or the corresponding configuration option or, as Pekka suggested, use __DIR__
to construct a filename relative to the directory of the current file.
精彩评论