PHP pathinfo
pathinfo() function to get the information on a file path.Introduction to the PHP pathinfo() function
The PHP pathinfo() function accepts a file path and returns its components:
pathinfo ( string $path , int $flags = PATHINFO_ALL ) : array|stringCode language: PHP (php)
The pathinfo() function has two parameters:
$pathis the file path from which you want to get the information.$flagsparameter specifies the part element to return.
The following table shows the valid flag values:
| Flag | Meaning |
|---|---|
PATHINFO_DIRNAME | Return the directory name |
PATHINFO_BASENAME | Return the base name |
PATHINFO_EXTENSION | Return the file extension |
PATHINFO_FILENAME | Return the file name (without the extension) |
If you don’t pass the $flag argument, the pathinfo() function will return all components of a file path.
PHP pathinfo() function examples
Let’s take some examples of using the pathinfo() function.
1) Using the pathinfo() function to get all components of a file path
The following example uses the pathinfo() function to get the components of a file path:
$path = 'htdocs/phptutorial/index.php';
$parts = pathinfo($path);
print_r($parts);
Code language: HTML, XML (xml)
Output:
Array
(
[dirname] => htdocs/phptutorial
[basename] => index.php
[extension] => php
[filename] => index
)Code language: PHP (php)
2) Using the pathinfo() function to get only a specific component of a file path
The following example uses the pathinfo() function get the basename of a file path:
$path = 'htdocs/phptutorial/index.php';
$basename = pathinfo($path, PATHINFO_BASENAME);
echo $basename;
Code language: HTML, XML (xml)
Output:
index.phpCode language: CSS (css)
3) Using the pathinfo() function to get the path components of a dot-file path
The following example uses the pathinfo() function to get components of the path of a dot-file:
$path = '/htdocs/phptutorial/.gitignore';
$parts = pathinfo($path);
print_r($parts);
Code language: HTML, XML (xml)
Output:
Array
(
[dirname] => /htdocs/phptutorial
[basename] => .gitignore
[extension] => gitignore
[filename] =>
)Code language: PHP (php)
Summary
- Use the PHP
pathinfo()function to get the components of a file path including dirname, basename, filename, and extesion.