我如何获取文件的绝对路径

时间:2022-07-02 02:40:08

say i have a file /var/www/foo/test.php

说我有一个文件/var/www/foo/test.php

how do i find out it's path from within it. i'm trying to create an "Add To Include Path" action, and for that i need absolute paths.

我如何从中发现它的路径。我正在尝试创建一个“添加到包含路径”操作,为此我需要绝对路径。

7 个解决方案

#1


Note: I am leaving my original answer intact, but don't use it. The solutions involving the __FILE__ constant are preferred.

注意:我原来的答案完好无损,但请不要使用它。涉及__FILE__常量的解决方案是首选。

You can use $_SERVER['DOCUMENT_ROOT'] to find the path to the current script. If you need the name of the .php file included, add on $_SERVER["SCRIPT_NAME"], like this:

您可以使用$ _SERVER ['DOCUMENT_ROOT']来查找当前脚本的路径。如果您需要包含.php文件的名称,请添加$ _SERVER [“SCRIPT_NAME”],如下所示:

$_SERVER['DOCUMENT_ROOT'].$_SERVER["SCRIPT_NAME"];

#2


You can use the magic constant, __FILE__

你可以使用魔法常量,__ FILE__

http://us2.php.net/manual/en/language.constants.predefined.php

#3


realpath(dirname(__FILE__))

#4


This will be provided as a server variable:

这将作为服务器变量提供:

$_SERVER["DOCUMENT_ROOT"];

#5


this_file = $_SERVER["SCRIPT_NAME"];

#6


Try:

dirname(__FILE__);

It will give you the directory in which your currently file is located. File has the full path to your file: http://php.net/language.constants.predefined

它将为您提供当前文件所在的目录。 File具有文件的完整路径:http://php.net/language.constants.predefined

#7


__FILE__ outputs exactly what you need.

#1


Note: I am leaving my original answer intact, but don't use it. The solutions involving the __FILE__ constant are preferred.

注意:我原来的答案完好无损,但请不要使用它。涉及__FILE__常量的解决方案是首选。

You can use $_SERVER['DOCUMENT_ROOT'] to find the path to the current script. If you need the name of the .php file included, add on $_SERVER["SCRIPT_NAME"], like this:

您可以使用$ _SERVER ['DOCUMENT_ROOT']来查找当前脚本的路径。如果您需要包含.php文件的名称,请添加$ _SERVER [“SCRIPT_NAME”],如下所示:

$_SERVER['DOCUMENT_ROOT'].$_SERVER["SCRIPT_NAME"];

#2


You can use the magic constant, __FILE__

你可以使用魔法常量,__ FILE__

http://us2.php.net/manual/en/language.constants.predefined.php

#3


realpath(dirname(__FILE__))

#4


This will be provided as a server variable:

这将作为服务器变量提供:

$_SERVER["DOCUMENT_ROOT"];

#5


this_file = $_SERVER["SCRIPT_NAME"];

#6


Try:

dirname(__FILE__);

It will give you the directory in which your currently file is located. File has the full path to your file: http://php.net/language.constants.predefined

它将为您提供当前文件所在的目录。 File具有文件的完整路径:http://php.net/language.constants.predefined

#7


__FILE__ outputs exactly what you need.