Get Directory Path from File Path using PHP dirname

Extracting the directory name from a complete file path is a common task in PHP development. This article explains how to use PHP’s built-in dirname() function to quickly and securely retrieve the parent directory path from a full file path, complete with practical code examples.

Understanding the PHP dirname() Function

The dirname() function in PHP takes a string containing the path to a file or directory and returns the parent directory’s path.

Syntax:

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

Basic Example

To get the immediate parent directory of a file, pass the file path as the first argument to dirname():

<?php
$filePath = "/var/www/html/images/profile.png";

// Get the immediate parent directory
$directoryPath = dirname($filePath);

echo $directoryPath; 
// Output: /var/www/html/images
?>

Going Up Multiple Levels

If you need to go up multiple directory levels, you can use the second argument ($levels). For example, to get the directory that is two levels above the file:

<?php
$filePath = "/var/www/html/images/profile.png";

// Go up 2 levels
$twoLevelsUp = dirname($filePath, 2);

echo $twoLevelsUp; 
// Output: /var/www/html
?>

Before PHP 7.0, you had to nest the function to achieve this (e.g., dirname(dirname($filePath))). Using the $levels parameter is now the recommended and cleaner approach.

How dirname() Handles Edge Cases