I'm having trouble understanding the ruleset regarding PHP relative include paths. If I run file A.PHP- and file A.PHP includes file B.PHP which includes file C.PHP, should the relative path to C.PHP be in relation to the location of B.PHP, or to the location of A.PHP? That is, does it matter which file the include is called from, or only what the current working directory is- and what determines the current working directory?
By using include paths, you can centralize code that your web site frequently uses. Additionally, some features, such as PEAR, require you to set the include path so PHP can locate the appropriate files.
Solution(By Examveda Team) The PHP file is either an absolute or relative path to a PHP script instead of the usual . js file.
The include (or require ) statement takes all the text/code/markup that exists in the specified file and copies it into the file that uses the include statement. Including files is very useful when you want to include the same PHP, HTML, or text on multiple pages of a website.
The include() and require() statement allow you to include the code contained in a PHP file within another PHP file. Including a file produces the same result as copying the script from the file specified and pasted into the location where it is called.
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With