PHP Filesystem dirname() Function
The PHP Filesystem dirname() function is used to get the directory part of a file path. It is useful when working with file paths and want to keep the directory path apart from the file name. The dirname() returns the path of the directory that contains the file you specify as a file path. Also, you can choose how many directory levels you want to go over.
The common use cases of dirname() function is to organizing file paths, navigating directories, and to manage Filesystem structures in our PHP apps.
Syntax
Below is the syntax of the PHP Filesystem dirname() function −
string dirname ( string path, int levels )
Parameters
The parameters are needed to use the dirname() function are mentioned below −
| Sr.No | Parameter & Description |
|---|---|
| 1 |
path(Required) This is the path of the file. |
| 2 |
levels(Optional) The number of directory levels you want to access is shown by this. By default, it returns 1, the immediate parent directory. If you set it to 2, it will move two levels, and so on. |
Return Value
The function returns a string containing the directory path of the given file path.
PHP Version
The dirname() function was first introduced as part of core PHP 4 and work well with the PHP 5, PHP 7, PHP 8.
Example
So first we will see the simple usage of the PHP Filesystem dirname() function. We will simply echo the direname() of the path specified inside the dirname function.
<?php
echo dirname("C:/PhpProject/index.php") . "\n";
echo dirname("/PhpProject/index.php");
?>
Output
This will produce the following result −
C:/PhpProject /PhpProject
Example
In the below code we will see how we can move multiple directory levels up in the given directory path by using the optional parameter of dirname() function.
<?php // define file path here $filePath = "/var/www/html/index.php"; // use dirname function and pass both the parameters $parentDirectory = dirname($filePath, 2); // print the parent directory detail echo $parentDirectory; ?>
Output
This will generate the below output −
/var/www
Example
This example shows you how you can use dirname() function to get the directory of the current script file. We have used the PHP magic constant __FILE__ is the entire path and filename of the script that is currently running. So, dirname(__FILE__) can be used to determine the directory name of the current script file.
<?php $sdir = dirname(__FILE__); echo $sdir; ?>
Output
This will lead to the following outcome −
/Applications/XAMPP/xamppfiles/htdocs/mac
Note
- The dirname() can be used on Unix and Windows-based platforms. It uses the \ for Windows and the / for Unix as directory separators.
- It can be used with absolute or relative paths. Documents will be provided, for example, using dirname("documents/file.txt").
Summary
Use dirname() to get the directory name of a file path. If you need to create a backup directory, use dirname() to get the parent directory and then create the backup folder inside of it.