获取当前脚本的绝对路径

inq*_*uam 238 php path include

我已经搜索了高低,并获得了许多不同的解决方案和包含信息的变量来获取绝对路径.但它们似乎在某些条件下工作而不在其他条件下工作.是否有一种银弹方式来获取PHP中执行脚本的绝对路径?对我来说,脚本将从命令行运行,但是,如果在Apache等中运行,解决方案应该也能正常运行.

澄清:最初执行的脚本,不一定是编码解决方案的文件.

zer*_*kms 265

__FILE__ 常量将为您提供当前文件的绝对路径.

更新:

问题已更改为询问如何检索最初执行的脚本而不是当前运行的脚本.唯一(??)可靠的方法是使用该debug_backtrace函数.

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];
Run Code Online (Sandbox Code Playgroud)

  • 注意:如果脚本位于apache2虚拟目录中,则返回的信息不会提供物理服务器上的实际路径位置.我希望这用于调试目的,甚至$ _SERVER变量也不提供此功能.例如,如果index.php存在于/ var/www/vpath1/html和/ var/www/html /和/ var/www/vpath2/html中,并且每个都虚拟映射到/ var/www/html,那么无论使用哪个虚拟服务器,都会看到/ var/www/html. (2认同)

T.T*_*dua 257

示例: https://(www.)example.com/subFolder/myfile.php?var=blabla#555

// ======= PATHINFO ====== //
$x = pathinfo($url);
$x['dirname']       https://example.com/subFolder
$x['basename']                                    myfile.php?
$x['extension']                                          php?k=blaa#12345 // Unsecure! also, read my notice about hashtag parts    
$x['filename']                                    myfile

// ======= PARSE_URL ====== //
$x = parse_url($url);
$x['scheme']        https
$x['host']                  example.com
$x['path']                             /subFolder/myfile.php
$x['query']                                                  k=blaa
$x['fragment']                                                      12345 // ! read my notice about hashtag parts

//=================================================== //
//========== self-defined SERVER variables ========== //
//=================================================== //
$_SERVER["DOCUMENT_ROOT"]   /home/user/public_html
$_SERVER["SERVER_ADDR"]     143.34.112.23
$_SERVER["SERVER_PORT"]     80(or 443 etc..)
$_SERVER["REQUEST_SCHEME"]  https                                         //similar: $_SERVER["SERVER_PROTOCOL"] 
$_SERVER['HTTP_HOST']               example.com (or with WWW)             //similar: $_SERVER["ERVER_NAME"]
$_SERVER["REQUEST_URI"]                           /subFolder/myfile.php?k=blaa
$_SERVER["QUERY_STRING"]                                                k=blaa
__FILE__                    /home/user/public_html/subFolder/myfile.php
__DIR__                     /home/user/public_html/subFolder              //same: dirname(__FILE__)
$_SERVER["REQUEST_URI"]                           /subFolder/myfile.php?k=blaa
parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH)  /subFolder/myfile.php 
$_SERVER["PHP_SELF"]                              /subFolder/myfile.php

// ==================================================================//
//if "myfile.php" is included in "PARENTFILE.php" , and you visit  "PARENTFILE.PHP?abc":
$_SERVER["SCRIPT_FILENAME"] /home/user/public_html/parentfile.php
$_SERVER["PHP_SELF"]                              /parentfile.php
$_SERVER["REQUEST_URI"]                           /parentfile.php?abc
__FILE__                    /home/user/public_html/subFolder/myfile.php

// =================================================== //
// ================= handy variables ================= //
// =================================================== //
//If site uses HTTPS:
$HTTP_or_HTTPS = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off') || $_SERVER['SERVER_PORT']==443) ? 'https://':'http://' );            //in some cases, you need to add this condition too: if ('https'==$_SERVER['HTTP_X_FORWARDED_PROTO'])  ...

//To trim values to filename, i.e. 
basename($url)              myfile.php

//excellent solution to find origin
$debug_files = debug_backtrace();       
$caller_file = count($debug_files) ? $debug_files[count($debug_files) - 1]['file'] : __FILE__;
Run Code Online (Sandbox Code Playgroud)

注意!:

  • hashtag(#...)无法从PHP(服务器端)检测到URL部分.为此,请使用JavaScript.
  • DIRECTORY_SEPARATOR返回\Windows类型的托管,而不是/.



对于WordPress

//(let's say, if wordpress is installed in subdirectory:  http://example.com/wpdir/)
home_url()                       http://example.com/wpdir/        //if is_ssl() is true, then it will be "https"
get_stylesheet_directory_uri()   http://example.com/wpdir/wp-content/themes/THEME_NAME  [same: get_bloginfo('template_url') ]
get_stylesheet_directory()       /home/user/public_html/wpdir/wp-content/themes/THEME_NAME
plugin_dir_url(__FILE__)         http://example.com/wpdir/wp-content/themes/PLUGIN_NAME
plugin_dir_path(__FILE__)        /home/user/public_html/wpdir/wp-content/plugins/PLUGIN_NAME/  
Run Code Online (Sandbox Code Playgroud)

  • 这是迄今为止我在整个互联网上看到的获取部分或全部文件路径的方法示例的最全面列表。 (2认同)

rik*_*rik 238

echo realpath(dirname(__FILE__));
Run Code Online (Sandbox Code Playgroud)

如果将其放在包含的文件中,则会打印此包含的路径.要获取父脚本的路径,请替换__FILE__$_SERVER['PHP_SELF'].但请注意,PHP_SELF存在安全风险!

  • 这里有什么样的真实路径? (13认同)
  • @col.Shrapnel:"自PHP 4.0.2起,`__ FILE__`总是包含一个解析了符号链接的绝对路径,而在旧版本中,它在某些情况下包含相对路径." 加上"dirname()"对输入字符串进行天真操作,并且不知道实际的文件系统或路径组件,例如"..". (11认同)
  • 哦,4.0.2.上世纪? (6认同)
  • 使用 `$_SERVER['PHP_SELF']` 有什么安全风险?因为人们回显它并且它包含可能是恶意的 URL? (2认同)
  • @rik:还有什么安全问题会导致`PHP_SELF` ?? (2认同)

Got*_*bel 38

__DIR__
Run Code Online (Sandbox Code Playgroud)

手册:

该文件的目录.如果在include中使用,则返回包含文件的目录.这相当于dirname(__FILE__).除非它是根目录,否则此目录名称没有尾部斜杠.
__FILE__ 始终包含已解析符号链接的绝对路径,而在旧版本(4.0.2)中,它包含在某些情况下的相对路径.

注意:__DIR__在PHP 5.3.0中添加.


Sal*_*n A 28

正确的解决方案是使用该get_included_files功能:

list($scriptPath) = get_included_files();
Run Code Online (Sandbox Code Playgroud)

这将为您提供初始脚本的绝对路径,即使:

  • 此功能放在包含的文件中
  • 当前工作目录与初始脚本的目录不同
  • 该脚本使用CLI执行,作为相对路径

这是两个测试脚本; 主脚本和包含文件:

# 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;
}
Run Code Online (Sandbox Code Playgroud)

结果; 注意当前目录:

C:\>php C:\Users\Redacted\Desktop\main.php
The script being executed is C:\Users\Redacted\Desktop\main.php
Run Code Online (Sandbox Code Playgroud)


pka*_*cki 21

如果你想获得当前工作目录使用getcwd()

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

__FILE__将返回带有文件名的路径,例如在XAMPP C:\xampp\htdocs\index.php而不是C:\xampp\htdocs\


Sul*_*nos 8

dirname(__FILE__) 
Run Code Online (Sandbox Code Playgroud)

将给出 您要求路由的当前文件的绝对路由,即服务器目录的路由.

示例文件:

www/http/html/index.php; 如果您将此代码放在index.php中,它将返回:

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

www/http/html/class/myclass.php; 如果您将此代码放在myclass.php中,它将返回:

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


Mat*_*ore 7

请使用以下内容:

echo __DIR__;
Run Code Online (Sandbox Code Playgroud)


min*_*jul 5

`realpath(dirname(__FILE__))` 
Run Code Online (Sandbox Code Playgroud)

它为您提供当前脚本(放置此代码的脚本)目录,而不是斜杠.如果要包含具有结果的其他文件,这一点很重要


bli*_*f77 5

这是我为此专门编写的一个有用的 PHP 函数。正如最初的问题所阐明的那样,它返回执行初始脚本的路径- 而不是我们当前所在的文件。

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)


Pao*_*olo 5

获得最初执行的脚本(在该脚本以及include,中包含的任何其他脚本中require)的绝对路径的一种简单方法require_once是使用常量并在主脚本开头存储当前脚本路径:

define( 'SCRIPT_ROOT', __FILE__ );
Run Code Online (Sandbox Code Playgroud)

当有一个“主”脚本包含include所有其他需要的脚本时,上面的解决方案是合适的,就像大多数Web 应用程序、工具和 shell 脚本一样。

如果情况并非如此,并且可能有多个“初始脚本”,那么为了避免重新定义并将正确的路径存储在常量中,每个脚本可以以以下方式开头:

if( ! defined( 'SCRIPT_ROOT' ) ) {
    define( 'SCRIPT_ROOT`, __FILE__ );
}
Run Code Online (Sandbox Code Playgroud)

关于(当前)接受的答案的注释:

答案指出最初执行的脚本路径是 . 返回的数组的第一个元素get_included_files()

这是一个聪明而简单的解决方案,并且在撰写本文时(我们几乎已经达到 PHP 7.4.0)它确实有效

然而,通过查看文档,没有提到最初执行的脚本是 .返回的数组的第一get_included_files()项。

我们只读

最初调用的脚本被视为“包含文件”,因此它将与 include 和 family 引用的文件一起列出。

在撰写本文时,“最初调用的脚本”是数组中的第一个,但从技术上讲,不能保证这在将来不会改变。


realpath()关于、__FILE__和 的注释__DIR__

其他人在他们的答案中建议使用__FILE__, __DIR__, dirname(__FILE__), realpath(__DIR__)...

dirname(__FILE__)等于__DIR__(在 PHP 5.3.0 中引入),所以只需使用__DIR__.

和始终都是绝对路径__FILE__,因此没有必要。__DIR__realpath()