Gmail / Facebook Style Chat Application
Details Live Demo Download

Posted: Sunday 30th of December 2012

How to get the Extension of a File Using PHP

This tutorial teaches you how to get the extension of any file for instance, gif from image.gif or any other file of your choice using PHP.
There are situations where you may need to get the extension of a given file for a certain purpose.
You may need to get the extension of the file in order to re-size it or you may need to check to see if an uploaded file has a particular extension so as to perform a certain task.
There are numerous ways to do this using PHP.
You can check the physical file type, you can use string position to count in from the end of the string, you can use a regular expression to find the extension, or you can use explode to split the string and then count the array and use the last value in the array as the extension.
All depends on your choice of coding operation and the security requirements.

You may download the script if you like what you see.

How to get the Extension of a File Using PHP

Below are PHP Codes with six different ways of getting the extensions of any given files and one way of getting the file name using the pathinfo method.



//This is the file name from which we are going to get its extension and display it to the user on the screen
$my_file_name = "image.jpg";

/* First Approach "explode/end" */
$first_extension = end(explode('.', $my_file_name));
echo "1 ".$first_extension;

/* Second Approach "strrchr" */
$second_extension = substr(strrchr($my_file_name, '.'), 1);
echo "<br><br>2 ".$second_extension;

/* Third Approach "strrpos" */
$third_extension = substr($my_file_name, strrpos($my_file_name, '.') + 1);
echo "<br><br>3 ".$third_extension;

/* Forth Approach "preg_replace" */
$forth_extension = preg_replace('/^.*\.([^.]+)$/D', '$1', $my_file_name);
echo "<br><br>4 ".$forth_extension;

/* Fifth Approach "split" */
$fifth_extension = split("[/\\.]", $my_file_name);
$fifth_extension_counter = count($fifth_extension)-1;
$fifth_extension_displayer = $fifth_extension[$fifth_extension_counter];
echo "<br><br>5 ".$fifth_extension_displayer;

/* Sixth Approach "pathinfo" */
$sixth_extension = pathinfo($my_file_name, PATHINFO_EXTENSION);
echo "<br><br>6 ".$sixth_extension;

/* Finally, get the File Name using "pathinfo" */
$get_the_filename = pathinfo($my_file_name, PATHINFO_FILENAME);
echo "<br><br><b>Filename:</b> ".$get_the_filename;


That's it guys...



Announcement x
Dear Users and Clients,

This is to inform you that we have recently updated our website generally.

If you experience any problem viewing any part of this website or if you notice that any of our scripts or tutorials are not functioning properly as should be, please click on the Contact Link at the top of this page to report the issue to us.

Our priority is to give you the best of service!

Thank You,
The Vasplus Team