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

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


当前回答

请使用下面的方法:

echo __DIR__;

其他回答

如果你正在寻找相对于服务器根目录的绝对路径,我发现这很有效:

$_SERVER['DOCUMENT_ROOT'] . dirname($_SERVER['SCRIPT_NAME'])
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 __DIR__;

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

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

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

这就是我所使用的,它在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']);
}