What is dirname in PHP?
PHP offers many functions for directory and file manipulation. The dirname function returns the path of the parent directory of the path specified in the parameter.
You can set the level of the desired directory in the second parameter. For example, the parent directory’s parent directory would be level 2.
Syntax
The syntax of the function is shown below:
dirname(string $path, int $levels): string
Parameters
The dirname() function takes two parameters:
path: This parameter is required. It is a string containing the path of the directory whose parent directory path is required.levels: This parameter is optional. It specifies the number of levels to go up to reach the intended parent directory. By default,levelsis set to1(the immediate parent directory).
Return value
The dirname() function returns the path of the parent directory specified by the parameters.
Code
The following code shows how we can use the dirname() function.
<?phpecho "Path of current directory:\nd:/edpresso/shot.php\n"; // \n is used to add a newlineecho "Parent directory of shot.php:\n";echo dirname("d:/edpresso/shot.php") . "\n";echo "Parent directory of shot.php, level 2:\n";echo dirname("d:/edpresso/shot.php", 2) . "\n";?>
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved