PHP获取当前目录的名称

r55awzrz  于 2023-01-08  发布在  PHP
关注(0)|答案(9)|浏览(134)

我有一个php页面内的一个文件夹在我的网站。
我需要将当前目录的名称添加到变量中,例如:

$myVar = current_directory_name;

这可能吗?

jaxagkaj

jaxagkaj1#

getcwd();

dirname(__FILE__);

或(PHP5)

basename(__DIR__)

http://php.net/manual/en/function.getcwd.php
http://php.net/manual/en/function.dirname.php
您可以使用basename()来获取路径的尾部:)
在您的情况下,我会说您最有可能使用getcwd(),当您有一个需要包含另一个库的文件并且该文件包含在另一个库中时,dirname(__FILE__)会更有用。
例如:

main.php
libs/common.php
libs/images/editor.php

common.php中,您需要使用editor.php中的函数,因此使用
common.php

require_once dirname(__FILE__) . '/images/editor.php';

main.php

require_once libs/common.php

这样,当common.php是main.php中的require'd时,在common.php中调用require_once将正确地包括images/editor.php中的editor.php,而不是试图在当前运行main.php的目录中查找。

igsr9ssn

igsr9ssn2#

仅获取脚本执行所在目录的名称:

//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"
np8igboo

np8igboo3#

可以使用dirname(__FILE__)获取当前文件目录的路径。
示例:/path_to/your_dir/your_file.php

// use dirname to get the directory of the current file
$path = dirname(__FILE__);
// $path here is now /path_to/your_dir

// split directory into array of pieces
$pieces = explode(DIRECTORY_SEPARATOR, $path);
// $pieces = ['path_to', 'your_dir']

// get the last piece
echo $pieces[count($pieces) - 1];
// result is: your_dir
nnvyjq4y

nnvyjq4y4#

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only
i5desfxk

i5desfxk5#

其实我发现最好的解决办法是这样的:

$cur_dir = explode('\\', getcwd());
echo $cur_dir[count($cur_dir)-1];

如果您目录是www\var\路径*当前路径*
则返回当前路径

mdfafbf1

mdfafbf16#

第一个月
库文件/图像/index.php
结果:图像

toiithl6

toiithl67#

要获取当前目录的名称,我们可以使用getcwd()dirname(__FILE__),但getcwd()dirname(__FILE__)不是同义词。它们的作用与它们的名称完全相同。如果您的代码是通过引用其他目录中的另一个文件中的类来运行的,那么这两个方法将返回不同的结果。
例如,如果我正在调用一个类,从那里调用这两个函数,并且这个类存在于/index.php的某个/controller/goodclass.php中,那么**getcwd()将返回'/dirname(__FILE__)将返回/controller**。

9cbw7uwe

9cbw7uwe8#

我使用这一行来获取实际的文件目录名,而不带路径。(适用于Windows)

substr(dirname(__FILE__), strrpos(dirname(__FILE__), '\\') + 1)

我对它做了一点修改,以便也能在Linux上工作

substr(dirname(__FILE__), strrpos(str_replace('\\', '/', dirname(__FILE__)), '/') + 1)
kdfy810k

kdfy810k9#

基本名称(getcwd());//只返回当前工作目录名。

相关问题