PHP pathinfo() Function
The PHP pathinfo() function returns information about a file path: either an associative array or a string, depending on flags.
Note: This function is locale aware. Therefore, to parse a path containing multibyte characters correctly, the matching locale must be set using the setlocale() function.
Syntax
pathinfo(path, flags)
Parameters
path |
Required. Specify the path being checked. |
flags |
Optional. Specify which array element to return. If not specified, it returns all elements. Possible values are:
|
Return Value
If the flags parameter is not passed, an associative array containing the following elements is returned: dirname, basename, extension (if any), and filename.
- If the path has more than one extension, PATHINFO_EXTENSION returns only the last one and PATHINFO_FILENAME only strips the last one.
- If the path does not have an extension, no extension element will be returned.
- If the basename of the path starts with a dot, the following characters are interpreted as extension, and the filename is empty.
If flags is present, returns a string containing the requested element.
Example: pathinfo() example
The example below shows the usage of pathinfo() function.
<?php //getting information about a file path $path_parts = pathinfo('/www/htdocs/inc/lib.inc.php'); //displaying the result print_r($path_parts); echo "\n"; //displaying each array element separately echo $path_parts['dirname'], "\n"; echo $path_parts['basename'], "\n"; echo $path_parts['extension'], "\n"; echo $path_parts['filename'], "\n"; ?>
The output of the above code will be similar to:
Array ( [dirname] => /www/htdocs/inc [basename] => lib.inc.php [extension] => php [filename] => lib.inc ) /www/htdocs/inc lib.inc.php php lib.inc
Example: using pathinfo() for a dot-file
Consider the example below where this function is used with a dot file.
<?php //getting information about a dot file $path_parts = pathinfo('/www/htdocs/inc/.test'); //displaying the result print_r($path_parts); ?>
The output of the above code will be similar to:
Array ( [dirname] => /www/htdocs/inc [basename] => .test [extension] => test [filename] => )
❮ PHP Filesystem Reference