dirname()
dirname() — Returns a parent directory's path.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
Given 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.
Signature
dirname(string $path, int $levels = 1): string
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| $path | string | A path. |
| $levels | int | The number of parent directories to go up. |
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. 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. ?>
Example
A runnable snippet:
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);
Output:
/etc / (or \ on Windows) . C:\ /usr
Changelog
| Version | Change |
|---|---|
| 8.0.0 | Now throws a ValueError if levels is less than 1. Previously, an E_WARNING was raised and null was returned. |
See also
basename(), pathinfo(), realpath()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page dirname() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.