How to detect the file extension in PHP?

Detecting file extension from file path is quite easy. PHP already has a built-in function that can check a file and return the extension name of that file. It is PHP pathinfo() function.

The pathinfo() function is a built-in function in PHP that returns the information about a file path as an array. We can detect the extension from that array as the array contains the file extension too.

Listing files from directory that have particular extensions in PHP

How To Read A Text File Line By Line In PHP?

For example, if we have an image “logo.png” which is inside the directory “images” then below is the code that will return the extension name:

 $file_info = pathinfo('images/logo.png');
 $file_extension = $file_info['extension'];
 echo $file_extension;

Another method of getting the file extension – method 2

Using the same pathinfo() PHP function, we can get the extension of a file with a different way. It will make the process simpler to detect the extension of a file as we don’t have to take the extension from the array. We are going to get the specific information directly instead of calling all. Just one line of code will directly return the extension. below is the code:

  $file_extension = pathinfo('images/logo.png', PATHINFO_EXTENSION);
  echo $file_extension;

You will able to see the extension name on the web page.

Leave a Reply

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