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/htmlThis example extracts the directory from an absolute Unix path.
Example 2
$path = "../img/pic.jpg";
$dir = dirname($path);
echo $dir;Result:
../imgHere 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/htdocsThis demonstrates handling a Windows‑style file path.
Example 4
$path = "/var/www/html";
$dir = dirname($path);
echo $dir;Result:
/var/wwwWhen 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.
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.