A simple way to have the absolute path of the initially executed script, in that script and any other script included with include
, require
, require_once
is by using a constant and storing there the current script path at beginning of the main script:
define( 'SCRIPT_ROOT', __FILE__ );
The solution above is suitable when there is a single "main" script that include
s every other needed script, as in most may web applications, tools and shell scripts.
If that's not the case and there may be several "intital scripts" then to avoid redefinitions and to have the correct path stored inside the constant each script may begin with:
if( ! defined( 'SCRIPT_ROOT' ) ) {
define( 'SCRIPT_ROOT`, __FILE__ );
}
A note about the (currently) accepted answer:
the answer states that the initially executed script path is the first element of the array returned by get_included_files()
.
This is a clever and simple solution and -at the time of writing- (we're almost at PHP 7.4.0) it does work.
However by looking at the documentation there is no mention that the initially executed script is the first item of the array returned by get_included_files()
.
We only read
The script originally called is considered an "included file," so it will be listed together with the files referenced by include and family.
At the time of writing the "script originally called" is the first one in the array but -technically- there is no guarantee that this won't change in the future.
A note about realpath()
, __FILE__
, and __DIR__
:
Others have suggested in their answers the use of __FILE__
, __DIR__
, dirname(__FILE__)
, realpath(__DIR__)
...
dirname(__FILE__)
is equal to __DIR__
(introduced in PHP 5.3.0), so just use __DIR__
.
Both __FILE__
and __DIR__
are always absolute paths so realpath()
is unnecessary.