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

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


当前回答

正确的解决方案是使用get_included_files函数:

list($scriptPath) = get_included_files();

这将给你初始脚本的绝对路径,即使:

这个函数被放置在一个包含的文件中 当前工作目录与初始脚本目录不同 脚本以相对路径的形式在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;
}

结果是;注意当前目录:

C:\>php C:\Users\Redacted\Desktop\main.php
The script being executed is C:\Users\Redacted\Desktop\main.php

其他回答

`realpath(dirname(__FILE__))` 

它为您提供当前脚本(您放置此代码的脚本)目录,不带后面的斜杠。 如果您想在结果中包含其他文件,这一点很重要

这是我为此写的一个有用的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;
}

请使用下面的方法:

echo __DIR__;
dirname(__FILE__) 

将给出当前文件的绝对路由,从您正在要求的路由,您的服务器目录的路由。

文件示例:

www / http / html / index . php;如果你把这段代码放在index.php中,它将返回:

<?php 回声目录名(__FILE__);返回:www/http/html/

www / http / html /类/ myclass.php;如果你把这段代码放在myclass.php中,它将返回:

<?php 回声目录名(__FILE__);返回:www/http/html/class/

__DIR__

摘自手册:

文件的目录。如果在包含中使用,则返回所包含文件的目录。这相当于dirname(__FILE__)。除非是根目录,否则该目录名没有后面的斜杠。

__FILE__总是包含一个符号链接解析的绝对路径,而在旧版本(高于4.0.2)中,在某些情况下它包含相对路径。

注意:__DIR__是在PHP 5.3.0中添加的。