In php, if i have a file that requires a file from a subdirectory like:
require('directory/file.php');
and file.php
wants to require another file in its own directory, is the path relative to file.php
or the file that it is included in?
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 require() function is used to include a PHP file into another irrespective of whether the file is included before or not. The require_once() will first check whether a file is already included or not and if it is already included then it will not include it again.
The require() function will stop the execution of the script when an error occurs. The include() function does not give a fatal error. The include() function is mostly used when the file is not required and the application should continue to execute its process when the file is not found.
The require_once keyword is used to embed PHP code from another file. If the file is not found, a fatal error is thrown and the program stops. If the file was already included previously, this statement will not include it again.
It's relative to the main script, in this case A.php. Remember that require()
just inserts code into the currently running script.
That is, does it matter which file the
require()
is called from
No.
If you want to make it matter, and do an require()
relative to B.php, use the __FILE__
constant (or __DIR__
since PHP 5.3) which will always point to the literal current file that that line if code is located in.
include(dirname(__FILE__)."/C.PHP");
It's relative to the original requiring file if that makes sense.
So, if you have a file called index which looks like this:
require("./resources/functions.inc.php");
And then functions.inc.php would need to look like this:
require("./resources/anotherFunctionsFile.inc.php");
Rather than:
require("anotherFunctionsFile.inc.php);
But really you should be making use of the __DIR__
constant, which is always the directory the script is being ran from; it makes things a lot easier.
More information about __DIR__
and other constants: http://php.net/manual/en/language.constants.predefined.php
I hope that helps.
include(dirname(__FILE__).'/include.php');
REF : http://php.net/manual/en/language.constants.predefined.php
The full path and filename of the file. If used inside an include, the name of the included file is returned. Since PHP 4.0.2, FILE always contains an absolute path with symlinks resolved whereas in older versions it contained relative path under some circumstances.
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