Master PHP’s dirname() Function: Syntax, Parameters, and Real-World Examples

This article explains PHP’s dirname() function, covering its purpose, syntax, parameters, return value, and multiple practical code examples that demonstrate extracting directory paths from absolute, relative, and Windows-style file strings.

php Courses
php Courses
php Courses
Master PHP’s dirname() Function: Syntax, Parameters, and Real-World Examples

PHP is a widely used scripting language for web development that offers many built‑in functions to help developers handle tasks efficiently. One particularly useful function is dirname(), which returns the directory portion of a given path.

Syntax of dirname()

string dirname ( string $path [, int $levels = 1 ] )

Parameters

path

: required, the path string to be processed. levels: optional, number of directory levels to return; default is 1.

Return Value

Returns the directory path as a string.

Usage Examples

Example 1

$path = "/var/www/html/myfile.txt";
$dir = dirname($path);
echo $dir;

Output: /var/www/html The function extracts the directory part of the absolute path.

Example 2

$path = "../img/pic.jpg";
$dir = dirname($path);
echo $dir;

Output: ../img Works with relative paths, returning the parent directory.

Example 3

$path = "C:/xampp/htdocs/index.php";
$dir = dirname($path);
echo $dir;

Output: C:/xampp/htdocs Demonstrates usage on Windows file paths.

Example 4

$path = "/var/www/html";
$dir = dirname($path);
echo $dir;

Output: /var/www If the given path is itself a directory, dirname() returns the parent directory.

The dirname() function is a practical tool for extracting directory portions of paths, especially when dynamically generating file paths or handling file operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode ExamplesdirnameFile Paths
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.