In this guide, we will discuss the use of the pathinfo() function in PHP.
What is the pathinfo() Function in PHP?
The pathinfo() is a useful method in PHP that accepts the file path as a parameter and returns its component. This function is useful for file manipulation and handling in PHP. The returned string or an associative array has the following information related to the file path:
The syntax of using the pathinfo() function is as follows:
This function accepts the two parameters path and options. The path is the path of the file for which you want to get the information and options are optional parameters to specify the return information. If you don’t use any flag, this function returns all the components of your file.
The following are the valid flags that can be used in this function:
|PATHINFO_DIRNAME||It returns the directory or folder name of the file|
|PATHINFO_EXTENSION||It returns the extension of the file|
|PATHINFO_FILENAME||It returns the file name without an extension|
|PATHINFO_BASENAME||It returns the base name|
How to Use the pathinfo() Function in PHP?
The following example code snippets illustrate the usage of the pathinfo() function in PHP:
The below example uses the pathinfo() function to get all the information about the file path:
In the following example, we have specified the component of the file path. It will return the basename of the file only:
$path = '/sample/myfile.txt';
$basename = pathinfo($path, PATHINFO_BASENAME);
Here is another example that extracts the path information of an image file in the PHP code.
$file_path = 'sample/image.png';
$path_info = pathinfo($file_path);
echo "The directory name is: " .$path_info['dirname'] ."<br>";
echo "The basename is: " .$path_info['basename'] ."<br>";
echo "The extension of file is: " .$path_info['extension'] ."<br>";
echo "The filename is: " .$path_info['filename'] ."<br>";
You can use the pathinfo() function in PHP to get the basename, directory name, filename, and extension of the file. This function allows the developers to extract important information about the file path. The returned information can be used to check the file name, its type, and the location of the file. We have discussed the usage of the pathinfo() function of PHP in the above section of this guide.