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