PHP 8.4.2 Released!

dirname

(PHP 4, PHP 5, PHP 7, PHP 8)

dirname返回路径中的目录部分

说明

dirname(string $path, int $levels = 1): string

给出一个包含有指向一个文件的全路径的字符串,本函数返回去掉文件名后的目录名,且目录深度为 levels 级。

注意:

dirname() 纯粹基于输入字符串操作, 它不会受实际文件系统和类似 ".." 的路径格式影响。

警告

在 Windows 上,dirname() 假设当前设置的代码页,因此要查看具有多字节字符路径的正确目录名称,必须设置匹配的代码页。如果 path 包含当前代码页无效的字符,则 dirname() 的行为是未定义的。

在其它系统上,dirname() 假设 path 是以 ASCII 兼容编码进行编码的。否则函数的行为是未定义的。

参数

path

一个路径。

在 Windows 中,斜线(/)和反斜线(\)都可以用作目录分隔符。在其它环境下是斜线(/)。

levels

要向上的父目录数量。

整型,必须大于 0。

返回值

返回 path 的父目录。如果在 path 中没有斜线,则返回一个点('.'),表示当前目录。否则返回的是把 path 中结尾的 /component(最后一个斜线以及后面部分)去掉之后的字符串。

警告

Be careful when using this function in a loop that can reach the top-level directory as this can result in an infinite loop.

<?php
dirname
('.'); // Will return '.'.
dirname('/'); // Will return `\` on Windows and '/' on *nix systems.
dirname('\\'); // Will return `\` on Windows and '.' on *nix systems.
dirname('C:\\'); // Will return 'C:\' on Windows and '.' on *nix systems.
?>

更新日志

版本 说明
7.0.0 添加可选的 levels 参数。

示例

示例 #1 dirname() 例子

<?php
echo dirname("/etc/passwd") . PHP_EOL;
echo
dirname("/etc/") . PHP_EOL;
echo
dirname(".") . PHP_EOL;
echo
dirname("C:\\") . PHP_EOL;
echo
dirname("/usr/local/lib", 2);

以上示例的输出类似于:

/etc
/ (or \ on Windows)
.
C:\
/usr

参见

添加备注

用户贡献的备注 6 notes

up
49
y dot a dot dejong at singular dot of dot alumni dot utwente dot nl
10 years ago
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
up
36
tobylewis at mac dot com
19 years ago
Since the paths in the examples given only have two parts (e.g. "/etc/passwd") it is not obvious whether dirname returns the single path element of the parent directory or whether it returns the whole path up to and including the parent directory. From experimentation it appears to be the latter.

e.g.

dirname('/usr/local/magic/bin');

returns '/usr/local/magic' and not just 'magic'

Also it is not immediately obvious that dirname effectively returns the parent directory of the last item of the path regardless of whether the last item is a directory or a file. (i.e. one might think that if the path given was a directory then dirname would return the entire original path since that is a directory name.)

Further the presense of a directory separator at the end of the path does not necessarily indicate that last item of the path is a directory, and so

dirname('/usr/local/magic/bin/'); #note final '/'

would return the same result as in my example above.

In short this seems to be more of a string manipulation function that strips off the last non-null file or directory element off of a path string.
up
42
tapken at engter dot de
22 years ago
To get the directory of current included file:

<?php
dirname
(__FILE__);
?>

For example, if a script called 'database.init.php' which is included from anywhere on the filesystem wants to include the script 'database.class.php', which lays in the same directory, you can use:

<?php
include_once(dirname(__FILE__) . '/database.class.php');
?>
up
4
bobray at softville dot com
5 years ago
Be aware that if you call dirname(__FILE__) on Windows, you may get backslashes. If you then try to use str_replace() or preg_replace() to replace part of the path using forward slashes in your search pattern, there will be no match. You can normalize paths with $path = str_replace('\\', '/' ,$path) before doing any transformations
up
10
joe dot naylor at gmail dot com
16 years ago
The dirname function does not usually return a slash on the end, which might encourage you to create links using code like this:
$url = dirname($_SERVER['PHP_SELF']) . '/somepage.php';

However dirname returns a slash if the path you specify is the root, so $url in that case would become '//somepage.php'. If you put that URL as the action on a form, for example, submitting the form will try to go to http://somepage.php.

I ran into this when I wrote a site on a url with a path, www.somehost.com/client/somepage.php, where the code above works great, but then wanted to put it on a subdomain, client.somehost.com/somepage.php, where things started breaking.

The best solution would be to create a function that generates absolute URLs and use that throughout the site, but creating a safe_dirname function (and an htaccess rewrite to fix double-slashes just in case) fixed the issue for me:

<?php
function safe_dirname($path)
{
$dirname = dirname($path);
return
$dirname == '/' ? '' : $dirname;
}
?>
up
3
klugg this-is-junk at tlen dot pl
19 years ago
Attention with this. Dirname likes to mess with the slashes.
On Windows, Apache:

<?php
echo '$_SERVER[PHP_SELF]: ' . $_SERVER['PHP_SELF'] . '<br />';
echo
'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . '<br>';
?>

prints out

$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
To Top