"get absolute path of initially run script" Answer’s


The correct solution is to use the get_included_files function:

list($scriptPath) = get_included_files();

This will give you the absolute path of the initial script even if:

  • This function is placed inside an included file
  • The current working directory is different from initial script's directory
  • The script is executed with the CLI, as a relative path

Here are two test scripts; the main script and an included file:

# C:UsersRedactedDesktopmain.php
include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';

# C:UsersRedactedDesktopinclude.php
function echoScriptPath() {
    list($scriptPath) = get_included_files();
    echo 'The script being executed is ' . $scriptPath;

And the result; notice the current directory:

C:>php C:UsersRedactedDesktopmain.php
The script being executed is C:UsersRedactedDesktopmain.php
Wednesday, March 31, 2021
answered 11 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :