Backend Development 4 min read

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

This article explains PHP's dirname() function, detailing its syntax, parameters, return values, and providing four practical code examples that demonstrate extracting directory paths from absolute, relative, and Windows-style file paths, as well as handling paths that are already directories.

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 various 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 including the file name or trailing slash, making it valuable for dynamically generating file paths or performing file operations.

Syntax of dirname()

<code>string dirname ( string $path [, int $levels = 1 ] )</code>

Parameters

path : required, the path string to be processed.

levels : optional, the number of directory levels to return (default is 1).

Return Value

Returns the directory path as a string.

Usage of dirname() Function

Example 1

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

Result:

<code>/var/www/html</code>

In this example, the path /var/www/html/myfile.txt is provided, and dirname() extracts and returns the directory /var/www/html .

Example 2

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

Result:

<code>../img</code>

Here a relative path ../img/pic.jpg is used; dirname() returns the directory part ../img .

Example 3

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

Result:

<code>C:/xampp/htdocs</code>

This example demonstrates a Windows file path. The function returns C:/xampp/htdocs as the directory.

Example 4

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

Result:

<code>/var/www</code>

When the given path itself is a directory, dirname() still returns the parent directory; thus, for /var/www/html it returns /var/www .

The dirname() function is a highly practical tool in PHP for extracting directory parts of paths, especially useful in dynamic path generation and file handling scenarios.

backendweb developmentcode examplesfile 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.