How to Get File Extension From File Path in PHP

Sometimes we need to get file extension in code to validate file type or put some kind of rule on particular file upload, in that case, we need to first get the file extension of the file and then we can apply the rule or validate the file as per requirement.

In this article, we will explain how to get a file extension in PHP.

Although file validation is an important part when it comes to putting the functionality of file upload somewhere in the application. Using the below code snippet you can get any file extension or type and use in further development on the website.

The following are the multiple examples, by using them you can get the file extension in PHP.

Exmaple 1:

We can use explode PHP function to break the string or name of the file in the array and can get the last part of the array. That last part will be file extension.

<?php
   $filename = 'atcodex.com';
   $ext = explode('.', $filename);
   echo $ext[1];
?>

output

com

Exmaple 2:

With the help of explode function, you can break the string in an array and get the last array value using the PHP end function.

<?php
   $filename = 'atcodex.png';
   $ext = end(explode(".", $filename));
   echo $ext;
?>

output

png

Exmaple 3:

In the following code, you can use pathinfo PHP function to get file extension.

<?php
   $filename = 'atcodex.pdf';
   $ext = pathinfo($filename, PATHINFO_EXTENSION);
   echo $ext;
?>

output

pdf

Exmaple 4:

In the below code you can use substr and strrpos and strlen function to get the file extension.

In the below function, strlen finds the total length of the string and strrpos get the count of left-hand string from dot. and substr function grabs the part from the main string coz it gets input for start and end position from other functions.

<?php
  $filename = 'atcodex.exe';
  $ext = substr($filename, (strrpos($filename, '.')+1), strlen($filename));
  echo $ext;
?>

output

exe