PHP dirname

Summary: in this tutorial, you will learn how to use the PHP 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 ) : string
Code language: PHP (php)

The dirname() function has two parameters:

  • $path is the file or directory path in which you want to get the parent’s directory path.
  • $levels is the number of parent directories to go up. The $levels must 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:

<?php 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/public
Code language: plaintext (plaintext)

Summary

  • Use the PHP dirname() function to get the parent directory’s path of a file or directory path.
Did you find this tutorial useful?