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 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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
