PHP dirname
dirname() function to get the parent directory’s path of a file or directory path.Introduction to the PHP dirname() function
The dirname() function accepts a path and returns a parent directory’s path:
dirname ( string $path , int $levels = 1 ) : stringCode language: PHP (php)
The dirname() function has two parameters:
$pathis the file or directory path in which you want to get the parent’s directory path.$levelsis the number of parent directories to go up. The$levelsmust be an integer that is greater than zero.
The dirname() returns the parent directory’s path that is $levels up from the current directory.
Note that you can use both slash (/) and backslash (\) as the directory separator character on Windows and the forward-slash (/) on other environments such as Linux and macOS.
PHP dirname() function example
The following example uses the dirname() function to get the parent directory’s path:
echo '1.' , dirname("/htdocs/public") , PHP_EOL;
echo '2.' , dirname("/htdocs/") , PHP_EOL;
echo '3.' , dirname(".") , PHP_EOL;
echo '4.' , dirname("C:\\") , PHP_EOL;
echo '5.' , dirname("/htdocs/public/css/dev", 2);
Code language: HTML, XML (xml)
Output:
1./htdocs
2.\
3..
4.C:\
5./htdocs/publicCode language: plaintext (plaintext)
Summary
- Use the PHP
dirname()function to get the parent directory’s path of a file or directory path.