Appearance
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.
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 explode
php
<?php
$fileName = 'banner.jpg';
$fileNameParts = explode('.', $fileName);
$ext = end($fileNameParts);
echo $ext;
?>Find the Last Occurrence of ‘.’
The second approach detects the last occurrence of ‘.’, which returns ‘.jpg’. Afterwards, you need to remove the first character of a string using substr. As a result, the exact file extension is returned.
Here is an example:
php substr
php
<?php
$fileName = 'banner.jpg';
$ext = substr(strrchr($fileName, '.'), 1);
echo $ext;
?>Use strrpos
The next way uses strrpos to find the position of the last occurrence of ‘.’ inside a filename. By incrementing that position by 1, substr extracts the extension.
The example is shown below:
php strrpos
php
<?php
$fileName = 'banner.jpg';
$ext = substr($fileName, strrpos($fileName, '.') + 1);
echo $ext;
?>Use preg_replace
In this approach, you apply a regular expression search and replacement.
Here is an example:
php preg_replace
php
<?php
$fileName = 'banner.jpg';
$ext = preg_replace('/^.*\.([^.]+)$/', '$1', $fileName);
echo $ext;
?>Use pathinfo
The final approach uses the PHP pathinfo() function, which returns information about a file. If the second optional parameter is omitted, it returns an associative array containing dirname, extension, basename, and filename. If you pass a specific flag, it returns only that piece of information.
Here is an example:
php pathinfo function
php
<?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.