How to get a file extension in PHP

Today we’ll explain to you how to get a file extension in PHP. Getting a file extension is very useful for validating a file or file upload. Here, we’ll show you the different ways to get a file extension from PHP string.

Different ways to get a file extension in PHP

  1. Using Explode() function
  2. Using substr() and strrchr() function
  3. Using strrpos() function
  4. Using pathinfo() function

Let’s start with an example. Assume that we have an image named cluemediator.jpg.

1. Using Explode() function

We will explode the file variable with . and get the last element of an array using end() function.

2. Using substr() and strrchr() function

Here, we will find the last occurrence of . with the use of strrchr() function that returns the .jpg string. Then we need to remove the first character of the string using the substr() function, it will return the file extension jpg.

3. Using strrpos() function

In this way, first we will find the position of the last occurrence of . from the filename. Then increase that position by 1 so that it explodes a string from ..

4. Using pathinfo() function

This is a very simple way to get file extension using the pathinfo() function. It will return the information of a file i.e. directory name, basename, extension, and filename.

This function takes two parameters. First one is filepath and second one is optional parameter that is an option which you want from file path.

You can use the options as given below.

  • PATHINFO_DIRNAME – Returns the directory name
  • PATHINFO_BASENAME – Returns the base name
  • PATHINFO_EXTENSION – Returns the file extension
  • PATHINFO_FILENAME – Returns the file name

If we have not passed the second parameter options then it will return the array as shown below example.

That’s it for today.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *