This is a quick guide on how to get the extension of a file using PHP.
In this tutorial, we will be using PHP’s pathinfo function instead of one of those nasty error-prone ‘hacks’ that you will come across on the Internet.
Getting the extension.
The pathinfo function returns information about a given file path. You can use it to get the directory name, the base name, the file name and the extension. In our case, we want the extension.
Take a look at the following example:
//The file path. $filename = 'dir/test.txt'; //Get the extension using pathinfo $extension = pathinfo($filename, PATHINFO_EXTENSION); //var_dump the extension - the result will be "txt" var_dump($extension);
In the code above, we supplied the pathinfo function with the constant PATHINFO_EXTENSION. As a result, it returns the string “txt”.
What if there is no extension?
If there is no extension, then the pathinfo function will return an empty string:
//The file path. $filePath = 'path/to/file/empty'; //Attempt to get the extension. $extension = pathinfo($filePath, PATHINFO_EXTENSION); //var_dump var_dump($extension);
If you run the snippet above, you will see that the following is outputted:
Multiple periods / dots.
This approach will also work if the file in question has multiple periods or dots. Take a look at the following example:
//A filename with two periods. $fileName = 'folder/example.file.jpg'; //Get the extension. $extension = pathinfo($filePath, PATHINFO_EXTENSION); //$extension will contain the string "jpg" var_dump($extension);
In the example above, our filename contains two periods. However, the pathinfo function is still able to return the correct extension name.
If there is a chance that your filename might contain special multibyte characters, then you will need to set the matching locale information. This is because the pathinfo function is “locale aware.”
You can do this by using PHP’s setlocale function like so:
An example of simplified Chinese:
Hopefully, you found this guide useful!