Get the Directory Name with the dirname() Function in PHP
Learn how to use the dirname() function in PHP to extract the directory name from a file path. See examples and sample code to help you use this function in your PHP projects. Whether you need to include files from different directories or create a new file in a specific directory, dirname() is the perfect tool to get the job done.
The dirname()
function in PHP is used to get the directory name from a path. The function returns the directory name of the path specified as the parameter. Here is an example of how to use the dirname()
function:
<?php
$path = '/var/www/html/example.php';
$dirname = dirname($path);
echo $dirname;
// Output: '/var/www/html'
?>
In this example, the dirname()
function is passed the path /var/www/html/example.php
as a parameter. The function returns the directory name of the path, which is /var/www/html
. The result is then stored in the variable $dirname
and then printed out using the echo
statement.
Another example is getting the directory of the current file:
<?php
$dirname = dirname(__FILE__);
echo $dirname;
?>
The output will be the directory name where the current file resides in.
The dirname()
function can be useful when working with file paths and directories. For example, if you need to include a file from a different directory or create a new file in a specific directory, you can use the dirname()
function to determine the correct directory path.