How to get the Extension of a File Using PHP

extensionplayAs a PHP developer, there are times where you need to get the extension of a file. You may need to get the extension of a .jpg file so you can resize it or you may need to check to see if an uploaded file has a .pdf extension. With PHP there are a number of ways to do this. You can check the physical file type, you can use string position to count in from the end of the string, you could use a regular expression to find the extension, or I have even seen people use explode to split the string and then count the array and use the last value in the array as the extension.

Depending on the coding operation and the security level required I have used a variety of techniques. Generally, I find I use the physical file type or the string position method. Yesterday, I needed a quick and easy way to find the file extension of an FLV file when parsing a directory. I decided to look and see if there were any PHP functions that could help me with this task. It turns out there was. Below is the PHP code I used to find the extension of a .flv file but it could easily work for any type of file.

<?php
    //PATH INFO RETURNS: DIRNAME, BASENAME, EXTENSION, FILENAME FROM A PATH
    $details = pathinfo('videos/file.flv');
 
    //EXTRACT EXTENSION FROM THE DETAILS ARRAY CREATED BY PATH INFO
    $extension =  $details['extension'];
 
    //PRINT THE EXTENSION OF THE FILE
    echo($extension);
?>

This code can easily be adapted to run in a function or however you would like it. The pathinfo() function also can extract the directory name, the base name, and the filename from a path string. A very handy function if you’re doing a lot of directory work. I wish I would’ve come across it sooner.

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

I often use

Leave a comment

(required)

(required)