The pathinfo() is an inbuilt function which is used to return information about a path using an associative array or a string.
The returned array or string contains the following information:
- Directory name
- Basename
- Extension
The path and options are sent as a parameters to the pathinfo() function and it returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Syntax:
pathinfo(path, options)
Parameters Used:
The pathinfo() function in PHP accepts two parameters.
- path : It is a mandatory parameter which specifies the path of the file.
- options : It is an optional parameter which can used to restrict the elements returned by the pathinfo() function. By default it returns all the possible values which are directory name, basename, extension.
Possible values can be restricted using :- PATHINFO_DIRNAME – return only dirname
- PATHINFO_BASENAME – return only basename
- PATHINFO_EXTENSION – return only extension
Return Value:
It returns an associative array containing the following elements directory name, basename, extension if the options parameter is not passed.
Errors And Exceptions:
- PATHINFO_EXTENSION returns only the last extension, if the path has more than one extension.
- No extension element is returned, if the path does not have an extension.
- If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty.
Examples:
Input : print_r(pathinfo("/documents/gfg.txt")); Output : Array ( [dirname] => /documents [basename] => gfg.txt [extension] => txt ) Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_DIRNAME)); Output : /documents Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_EXTENSION)); Output : txt Input : print_r(pathinfo("/documents/gfg.txt", PATHINFO_BASENAME)); Output : gfg.txt
Below programs illustrate the pathinfo() function.
Suppose there is a file named “gfg.txt”
Program 1
php
<?php // returning information about // the path using pathinfo() function print_r( pathinfo ( "/documents/gfg.txt" )); ?> |
Output:
Array ( [dirname] => /documents [basename] => gfg.txt [extension] => txt )
Program 2
php
<?php // returning information about // the directoryname path using pathinfo() function print_r( pathinfo ( "/documents/gfg.txt" , PATHINFO_DIRNAME)); ?> |
Output:
/documents
Program 3
php
<?php // returning information about // the extension of path using pathinfo() function print_r( pathinfo ( "/documents/gfg.txt" , PATHINFO_EXTENSION)); ?> |
Output:
txt
Program 4
php
<?php // returning information about // the basename of path using pathinfo() function print_r( pathinfo ( "/documents/gfg.txt" , PATHINFO_BASENAME)); ?> |
Output:
gfg.txt