How to Get a File Extension in PHP

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.

Watch a course Learn object oriented PHP

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:

<?php

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

echo $ext;
?>

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:

<?php

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

echo $ext;
?>

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:

<?php

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

echo $ext;
?>

Use preg_replace

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

Here is an example:

<?php

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

echo $ext;
?>

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:

<?php

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

echo $ext;
?>

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.