Backend Development 4 min read

Understanding PHP dirname() Function with Syntax, Parameters, and Practical Examples

This article explains the PHP dirname() function, its syntax, parameters, return values, and demonstrates its usage through multiple code examples covering absolute, relative, and Windows paths as well as handling directory inputs.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Understanding PHP dirname() Function with Syntax, Parameters, 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.

Syntax of dirname()

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

Parameters

path : required, the path string to be processed.

levels : optional, the number of directory levels to return; defaults to 1.

Return Value

The function returns a string containing the directory path.

Usage Examples

Example 1

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

Result:

/var/www/html

This example extracts the directory from an absolute Unix path.

Example 2

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

Result:

../img

Here a relative path is used, and the function returns the relative directory.

Example 3

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

Result:

C:/xampp/htdocs

This demonstrates handling a Windows‑style file path.

Example 4

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

Result:

/var/www

When the provided path is itself a directory, dirname() returns its parent directory.

Overall, dirname() is a practical PHP function for extracting directory parts of paths, which is especially useful when dynamically generating file paths or performing file operations.

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