Why include __DIR__ in the require_once?
PHP scripts run relative to the current path (result of getcwd()
), not to the path of their own file. Using __DIR__
forces the include to happen relative to their own path.
To demonstrate, create the following files (and directories):
- file1.php
- dir/
- file2.php
- file3.php
If file2.php
includes file3.php
like this:
include `file3.php`.
It will work fine if you call file2.php
directly. However, if file1.php
includes file2.php
, the current directory (getcwd()
), will be wrong for file2.php
, so file3.php
cannot be included.
The current accepted answer does not fully explain the cause of using __DIR__
and in my opinion the answer is wrong.
I am gonna explain why do we really need this.
Suppose we have a file structure like this
- index.php
- file3.php -(content: hello fake world)
- dir/
- file2.php
- file3.php - (content: hello world)
If we include file3.php from file2.php and run file2.php directly, we will see the output hello world
.
Now when we include file2.php in index.php, when the code will start executing and it will see file2 again including file3 using include 'file3.php'
, at first the execution will look for file3 in the current execution directory (which is the same directory where index.php is present)..Since file3.php is present in that directory, it will include that file3.php
instead of dir/file3.php
and we will see the output hello fake world
instead of hello world
.
If file3.php would not exist in the same directory, it would then include the correct dir/file3.php
file which makes the accepted answer not valid because it states file3.php cannot be included
which is not true. It is included.
However, here comes the necessity of using __DIR__
. If we would use include __DIR__ . '/file3.php'
in file2.php, then it would include the correct file even though another file3.php is present in the parent directory.