PHP dirname

Created with Sketch.

PHP dirname

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:


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)



Code language: plaintext (plaintext)


  • Use the PHP dirname() function to get the parent directory’s path of a file or directory path.

Leave a Reply

Your email address will not be published. Required fields are marked *