PHP Function Reference

PHP dirname() Function



The PHP dirname() function returns a string containing the path of a file or directory, this function will return the parent directory's path that is levels up from the current directory.

Note: This function operates naively on the input string, and is not aware of the actual filesystem, or path components such as "..".

Syntax

dirname(path, levels)

Parameters

path

Required. Specify a path to check.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).
levels Required. Specify the number of parent directories to go up. This must be an integer greater than 0.

Return Value

Returns the path of a parent directory. If there are no slashes in path, a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.

Example: dirname() example

The example below shows the usage of dirname() function.

<?php
echo dirname("/usr/example/fig/1.jpg")."\n";
echo dirname("/usr/example/fig/")."\n";
echo dirname("/usr/example/")."\n";
echo dirname(".")."\n";
echo dirname("/usr/example/fig/local", 2)."\n";
?>

The output of the above code will be:

/usr/example/fig
/usr/example
/usr
.
/usr/example

❮ PHP Filesystem Reference