开发者

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 jus开发者_JAVA技巧t as well if run within Apache etc.

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


__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'];


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!


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:\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


__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.


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\


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/


Just use below :

echo __DIR__;


`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


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 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.


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'])


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.


try this on your script

echo getcwd() . "\n";


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']);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜