How to Get the File Extension in PHP

As a programmer, you may encounter a scenario where you need to extract the extension of a file.

In PHP, there are several methods you can use to get the file extension.

In this tutorial, we will discuss two of the most commonly used methods to get the file extension in PHP.


Using the pathinfo() Function

The pathinfo() function is one of the most straightforward ways to get the file extension in PHP.

This function takes the file path as an argument and returns an associative array that contains information about the path.

To get the file extension, we can use the ‘extension’ index of the array returned by the pathinfo() function.

Here’s an example of how to use the pathinfo() function to get the file extension:

$file = "/path/to/file.jpg";
$file_extension = pathinfo($file, PATHINFO_EXTENSION);
echo $file_extension;

In this example, the pathinfo() function takes the file path as an argument and returns an associative array with information about the path.

The second argument (PATHINFO_EXTENSION) specifies that we want to get the file extension.

The ‘extension’ index of the array returned by the pathinfo() function is then stored in the $file_extension variable.

Finally, we echo the $file_extension variable to display the file extension.

Using strrchr() Function

Another method to get the file extension in PHP is by using the strrchr() function.

This function returns the portion of a string that starts from the last occurrence of a specified character to the end of the string.

In this case, we’ll be using the dot (.) character as the specified character.

Here’s an example of how to use the strrchr() function to get the file extension:

$file = "/path/to/file.jpg";
$file_extension = substr(strrchr($file, "."), 1);
echo $file_extension;

In this example, the strrchr() function returns the portion of the string that starts from the last dot (.) character to the end of the string.

The substr() function then takes this result and returns all characters after the first character (which is the dot character).

The resulting string is then stored in the $file_extension variable and finally, we echo the $file_extension variable to display the file extension.


Conclusion

In this tutorial, we discussed two methods to get the file extension in PHP: using the pathinfo() function and using the strrchr() function.

Both methods are straightforward and easy to use, so choose the one that suits your needs best.

Regardless of the method you choose, getting the file extension in PHP is a critical aspect of programming that can be achieved with ease.