Backend Development 4 min read

Understanding PHP dirname() Function: Syntax, Parameters, Return Values, and Practical Examples

This article explains the PHP dirname() function, detailing its purpose, syntax, parameters, return values, and provides multiple code examples demonstrating how it extracts directory paths from absolute, relative, and Windows-style file paths, including handling of directory inputs.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP dirname() Function: Syntax, Parameters, Return Values, and Practical Examples

PHP is a widely used scripting language for web development, offering 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.

The dirname() function extracts the directory name from a path without the file name or trailing slash, making it handy for generating file paths dynamically or handling file operations.

Syntax:

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

Parameters:

$path (required): the path string to be processed.

$levels (optional): number of directory levels to go up; default is 1.

Return value:

Returns the directory path as a string.

Examples:

Example 1

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

Output:

/var/www/html

This extracts the directory /var/www/html from the absolute path.

Example 2

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

Output:

../img

Works with relative paths, returning ../img .

Example 3

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

Output:

C:/xampp/htdocs

Demonstrates usage on Windows 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.

Summary: The dirname() function is a practical tool in PHP for extracting the directory part of a path, useful in dynamic path generation and file manipulation.

BackendPHPphp-functionsfile pathdirname
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

login 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.