PHP: Get the extension of a file.

This is a quick guide on how to 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:

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:

If you run the snippet above, you will see that the following is outputted:

Empty PHP string

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:

In the example above, our filename contains two periods. However, the pathinfo function is still able to return the correct extension name.

Special characters.

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!

Facebook Comments