phppathinclude

Get absolute path of initially run script


I have searched high and low and get a lot of different solutions and variables containing info to get the absolute path. But they seem to work under some conditions and not under others. Is there one silver bullet way to get the absolute path of the executed script in PHP? For me, the script will run from the command line, but, a solution should function just as well if run within Apache etc.

Clarification: The initially executed script, not necessarily the file where the solution is coded.


Solution

  • One 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:


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

    # C:\Users\Redacted\Desktop\main.php
    include __DIR__ . DIRECTORY_SEPARATOR . 'include.php';
    echoScriptPath();
    
    # C:\Users\Redacted\Desktop\include.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:\Users\Redacted\Desktop\main.php
    The script being executed is C:\Users\Redacted\Desktop\main.php