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.
The syntax of the function is shown below:
dirname(string $path, int $levels): string
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).The dirname()
function returns the path of the parent directory specified by the parameters.
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";?>