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, levels is set to 1 (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.

<?php
echo "Path of current directory:\nd:/edpresso/shot.php\n"; // \n is used to add a newline
echo "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";
?>
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved