[php] 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.

This question is related to php path include

The answer is


echo realpath(dirname(__FILE__));

If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!


try this on your script

echo getcwd() . "\n";

dirname(__FILE__) 

will give the absolute route of the current file from which you are demanding the route, the route of your server directory.

example files :

www/http/html/index.php ; if you place this code inside your index.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/

www/http/html/class/myclass.php ; if you place this code inside your myclass.php it will return:

<?php echo dirname(__FILE__); // this will return: www/http/html/class/


If you're looking for the absolute path relative to the server root, I've found that this works well:

$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])

Just use below :

echo __DIR__;

__DIR__

From the manual:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ always contains an absolute path with symlinks resolved whereas in older versions (than 4.0.2) it contained relative path under some circumstances.

Note: __DIR__ was added in PHP 5.3.0.


Here's a useful PHP function I wrote for this precisely. As the original question clarifies, it returns the path from which the initial script was executed - not the file we are currently in.

/**
 * Get the file path/dir from which a script/function was initially executed
 * 
 * @param bool $include_filename include/exclude filename in the return string
 * @return string
 */ 
function get_function_origin_path($include_filename = true) {
    $bt = debug_backtrace();
    array_shift($bt);
    if ( array_key_exists(0, $bt) && array_key_exists('file', $bt[0]) ) {
        $file_path = $bt[0]['file'];
        if ( $include_filename === false ) {
            $file_path = str_replace(basename($file_path), '', $file_path);
        }
    } else {
        $file_path = null;
    }
    return $file_path;
}

realpath($_SERVER['SCRIPT_FILENAME'])

For script run under web server $_SERVER['SCRIPT_FILENAME'] will contain the full path to the initially called script, so probably your index.php. realpath() is not required in this case.

For the script run from console $_SERVER['SCRIPT_FILENAME'] will contain relative path to your initially called script from your current working dir. So unless you changed working directory inside your script it will resolve to the absolute path.


If you want to get current working directory use getcwd()

http://php.net/manual/en/function.getcwd.php

__FILE__ will return path with filename for example on XAMPP C:\xampp\htdocs\index.php instead of C:\xampp\htdocs\


This is what I use and it works in Linux environments. I don't think this would work on a Windows machine...

//define canonicalized absolute pathname for the script
if(substr($_SERVER['SCRIPT_NAME'],0,1) == DIRECTORY_SEPARATOR) {
    //does the script name start with the directory separator?
    //if so, the path is defined from root; may have symbolic references so still use realpath()
    $script = realpath($_SERVER['SCRIPT_NAME']);
} else {
    //otherwise prefix script name with the current working directory
    //and use realpath() to resolve symbolic references
    $script = realpath(getcwd() . DIRECTORY_SEPARATOR . $_SERVER['SCRIPT_NAME']);
}

Answer has been moved here - https://stackoverflow.com/a/26944636/2377343


__FILE__ constant will give you absolute path to current file.

Update:

The question was changed to ask how to retrieve the initially executed script instead of the currently running script. The only (??) reliable way to do that is to use the debug_backtrace function.

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];

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 includes every other needed script, as in most web applications.

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.


`realpath(dirname(__FILE__))` 

it gives you current script(the script inside which you placed this code) directory without trailing slash. this is important if you want to include other files with the result


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to path

Get Path from another app (WhatsApp) How to serve up images in Angular2? How to create multiple output paths in Webpack config Setting the correct PATH for Eclipse How to change the Jupyter start-up folder Setting up enviromental variables in Windows 10 to use java and javac How do I edit $PATH (.bash_profile) on OSX? Can't find SDK folder inside Android studio path, and SDK manager not opening Get the directory from a file path in java (android) Graphviz's executables are not found (Python 3.4)

Examples related to include

"Multiple definition", "first defined here" errors Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0 Include PHP file into HTML file Cannot open include file with Visual Studio How to make Apache serve index.php instead of index.html? Include php files when they are in different folders Already defined in .obj - no double inclusions What's the difference between including files with JSP include directive, JSP include action and using JSP Tag Files? What is the correct syntax of ng-include? Visual Studio can't 'see' my included header files