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

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


当前回答

__FILE__常量将给你当前文件的绝对路径。

更新:

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

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

其他回答

echo realpath(dirname(__FILE__));

如果将此文件放在包含的文件中,它将打印该包含的路径。要获得父脚本的路径,将__FILE__替换为$_SERVER['PHP_SELF']。但是请注意PHP_SELF是一个安全风险!

这就是我所使用的,它在Linux环境中工作。我认为这在Windows机器上行不通……

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

__FILE__常量将给你当前文件的绝对路径。

更新:

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

$stack = debug_backtrace();
$firstFrame = $stack[count($stack) - 1];
$initialFile = $firstFrame['file'];
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/

在你的脚本上试试这个

echo getcwd() . "\n";