270 of 410 menu

The dirname Function

The dirname function returns the path to the parent directory of the specified path. The first parameter is a string with the path, and the second optional parameter is the number of levels to go up.

Syntax

dirname(string $path, int $levels = 1): string

Example

Get the parent directory for the path:

<?php echo dirname('/var/www/html/index.php'); ?>

Code execution result:

'/var/www/html'

Example

Go up two directory levels:

<?php echo dirname('/var/www/html/index.php', 2); ?>

Code execution result:

'/var'

Example

Working with relative paths:

<?php echo dirname('images/photo.jpg'); ?>

Code execution result:

'images'

See Also

  • the basename function,
    which returns the filename
  • the pathinfo function,
    which returns information about the path
  • the realpath function,
    which returns the absolute path
byenru