How to get the extension of a file using PHP.

In this guide, we are going to show you how to get the extension of a file using PHP.

In the examples below, we will use PHP’s pathinfo function instead of one of those nasty, error-prone “hacks” that you will see elsewhere on the Internet.

Getting the file extension using PHP.

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 obviously 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 will return the string “txt”.

What if there is no extension?

If the file does not have an 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, it will print out the following:

Empty PHP string

What if there are multiple periods / dots?

This function will also work if the file in question has multiple periods or dots.

For 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);

If you look at the PHP code above, you will see that 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:

setlocale(LC_ALL, "en_US.UTF-8");

An example of simplified Chinese:

setlocale(LC_ALL, 'zh_CN.UTF-8');

Or, if the file names contain Russian characters:

setlocale(LC_ALL, 'ru_RU.UTF-8');