我到处搜索,得到了很多不同的解决方案和包含信息的变量,以获得绝对路径.但它们似乎在某些条件下有效,而在其他条件下无效.有没有一种灵丹妙药可以让你在PHP中获得执行脚本的绝对路径?对我来说,脚本将从命令行运行,但是,如果在Apache等中运行,解决方案也应该运行良好.
Clarification: The initially executed script, not necessarily the file where the solution is coded.
我到处搜索,得到了很多不同的解决方案和包含信息的变量,以获得绝对路径.但它们似乎在某些条件下有效,而在其他条件下无效.有没有一种灵丹妙药可以让你在PHP中获得执行脚本的绝对路径?对我来说,脚本将从命令行运行,但是,如果在Apache等中运行,解决方案也应该运行良好.
Clarification: The initially executed script, not necessarily the file where the solution is coded.
正确的解决方案是使用get_included_files
功能:
list($scriptPath) = get_included_files();
这将为您提供初始脚本的绝对路径,即使:
这里有两个测试脚本;主脚本和包含的文件:
# 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