This article demonstrates how to extract file extension in PHP.

1. Using pathinfo() function

The built-in function for getting the file extension is pathinfo() function. This function takes the path to be parsed and a flag, and returns path information depending on the flag. The flag can be one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION, or PATHINFO_FILENAME. As an example, consider the following code, which returns the file extension of a text file using pathinfo() with PATHINFO_EXTENSION flag.

Download  Run Code

 
If the specified path doesn’t contain an extension, pathinfo() returns an empty string. However, if the file contains multiple dots, PATHINFO_EXTENSION returns only the last extension, and PATHINFO_FILENAME only strips the last extension. Consider the filename file.tar.gz, which represents a file in the tar format that’s compressed with gz. For this file, PATHINFO_EXTENSION returns gz and PATHINFO_FILENAME returns file.tar.

Download  Run Code

 
Note that if no flag is specified to the pathinfo() function, an associative array is returned containing dirname, basename, extension, and filename keys. Also, if the basename of the path starts with a dot, the filename is considered empty, and the following characters get interpreted as an extension. For example,

Download  Run Code

 
It should also be noted that the pathinfo() function is locale aware. To correctly deal with a path containing multibyte characters, you should set the locale first using the setlocale() function.

2. Using SplFileInfo::getExtension() function

Another way of getting the extension is to use getExtension() from the SplFileInfo class. The idea is to create a new SplFileInfo object for the specified file and invoke the getExtension() function to get the file extension.

Download  Run Code

3. Using explode() function

Alternatively, you can split the path using the explode() function, with the dot character (.) as the separator. Then you can simply return the value of the last element of the returned array.

Download  Run Code

4. Using strrpos() + substr() function

A better option is to use the combination of strrpos() and substr() functions to extract the file extension in PHP. The idea is to find the position of the last occurrence of the dot character (.) within a path string using the “strrpos()” function, and then extract the substring that follows it using the substr() function. However, you might want to check if the specified path contains an extension before extracting it.

Download  Run Code

 
All the above solutions work in a similar way to the pathinfo() function. i.e., it returns gz for filename file.tar.gz, and test for filename .test.

That’s all there is to extracting file extension in PHP.