Appearance
How to Get the Absolute Path to the Initially Run Script in PHP
Using the get_included_files Function
The most reliable method for getting the absolute path to the initially run script in PHP is using the get_included_files() function combined with realpath().
Here is an example of its usage:
php
list($scriptPath) = get_included_files();
$scriptPath = realpath($scriptPath);After using this function, $scriptPath will contain the absolute path of the main script, even in the following cases:
- the code is located in an included file;
- the initial script directory differs from the current working directory;
- the script is executed via a relative path in the CLI.
Consider the following two files. One is the main script, and the other is an included file:
main.php
php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
echoScriptPath();include.php
php
function echoScriptPath() {
list($scriptPath) = get_included_files();
$scriptPath = realpath($scriptPath);
echo 'The script being run is ' . $scriptPath;
}The result will look as follows:
console
C:\> php C:/Users/Redacted/Desktop/main.php
The script being run is C:/Users/Redacted/Desktop/main.phpDescribing the get_included_files Function
This function is supported by PHP 4, PHP 5, and PHP 7+.
It returns an array containing the names of the required or included files. The initially called script is always the first element in this array. Note that get_included_files() preserves the exact path format used to invoke the script, which may be relative. Wrapping the result in realpath() ensures you get a normalized absolute path.
Files that are required or included multiple times will appear only once in the returned array.
For absolute path resolution, you can also use __FILE__ or $_SERVER['SCRIPT_FILENAME'] depending on your execution context.