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 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/htmlThis extracts the directory /var/www/html from the absolute path.
Example 2
$path = "../img/pic.jpg";
$dir = dirname($path);
echo $dir;Output:
../imgWorks with relative paths, returning ../img .
Example 3
$path = "C:/xampp/htdocs/index.php";
$dir = dirname($path);
echo $dir;Output:
C:/xampp/htdocsDemonstrates usage on Windows paths.
Example 4
$path = "/var/www/html";
$dir = dirname($path);
echo $dir;Output:
/var/wwwIf 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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.