Oihana PHP

directoryPath.php

Table of Contents

Functions

directoryPath()  : string
Returns the directory part of the path.

Functions

directoryPath()

Returns the directory part of the path.

directoryPath(string $path) : string

This function normalizes and extracts the parent directory from a file path. It handles edge cases not covered by PHP's built-in dirname(), such as:

  • Preserving trailing slashes in Windows root paths (e.g., "C:/")
  • Correctly handling URI schemes (e.g., "file:///path/to/file")
  • Supporting UNC (network) paths on Windows (e.g., "\server\share\folder")
  • Returning an empty string when no directory is applicable

This method is similar to PHP's dirname(), but handles various cases where dirname() returns a weird result:

  • dirname() does not accept backslashes on UNIX
  • dirname("C:/symfony") returns "C:", not "C:/"
  • dirname("C:/") returns ".", not "C:/"
  • dirname("C:") returns ".", not "C:/"
  • dirname("symfony") returns ".", not ""
  • dirname() does not canonicalize the result

This method fixes these shortcomings and behaves like dirname() otherwise.

The result is a canonical path.

Parameters
$path : string

The file path from which to extract the directory.

Tags
example

Unix-style paths

directoryPath('/var/www/html/file.txt'); // Returns '/var/www/html'

Windows-style paths

directoryPath('C:\Windows\System32\file.txt'); // Returns 'C:\Windows\System32'
directoryPath('D:/Program Files/My App/file.txt'); // Returns 'D:/Program Files/My App'

Paths with URI schemes

directoryPath('file:///home/user/doc.txt'); // Returns '/home/user'

Edge cases

directoryPath('file.txt'); // Returns ''
directoryPath(''); // Returns ''
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string —

The directory part of the path, or an empty string if no directory can be extracted.

On this page

Search results