How to Get a File Extension in PHP

  1. Explode a File Variable
  2. Find the Last Occurrence of ‘.’
  3. Use strrpos
  4. Use preg_replace
  5. Use pathinfo

In PHP, there exist various ways of getting a file extension. In our tutorial, we have chosen the 5 best ways that will help you to get a file extension straightforwardly.

Go ahead and choose the one that matches your project better.

Explode a File Variable

The first way is exploding a file variable and getting the last element of the array. That will be a file extension. Here is how you can do it:

$ext = end(explode('.', $fileName));

Find the Last Occurrence of ‘.’

In the framework of the second approach, we recommend detecting the last occurrence of ‘.’, which will return a ‘.jpg’. Afterwards, you need to remove the first character of a string using substr. As a result, the exact file extension ‘.jpg’ will be returned.

Here is an example:

$ext = substr(strrchr($fileName, '.'), 1);

Use strrpos

The next way is to use strrpos for detecting the position of the last occurrence of ‘.’ inside a file name, incrementing that position by 1 so that it explodes a string from (.).

The example is shown below:

$ext = substr($fileName, strrpos($fileName, '.') + 1);

Use preg_replace

In the framework of this approach, you should apply a regular expression reach and replacement.

Here is an example:

$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $fileName);

Use pathinfo

And, the final approach that we recommend is to use the PHP pathinfo() function. It is aimed at returning information about the file. In case the second optional parameter is not passed, an associative array will be returned. It will include the dirname, extension, basename, and filename. Once the second parameter is passed, then specific information will be returned.

Here is an example:

$fileName = 'banner.jpg';
$ext = pathinfo($fileName, PATHINFO_EXTENSION);

So, after learning about all the possible ways described above, you are free to choose the best one for you. In our opinion, the simplest, yet the most efficient way among all these options is the pathinfo() function.


Do you find this helpful?

Related articles