Getting a file’s extension is essential when working with uploads and other manipulations complying with files. You might have a user uploading a file and you need to rename the file before moving it from the temporary upload directory. In order to do so, you can obtain the file extension and then rename it to whatever you like. Below is a custom function I wrote which will help you to get the extension of any file using PHP.
if (!empty($filename)) {
$filename = strtolower($filename);
$extArray = split("[/\\.]", $filename);
$p = count($extArray) – 1;
$extension = $extArray[$p];
return $extension;
} else {
return false;
}
}
So basically, we split the name of the file on every dot (.). The PHP split() function creates an array of strings for us. We then take the string obtained after the last dot (.). Even though there might be more than one period within the filename, we know that the last string will be the extension.
Now, with the full file extension in your possession, you can continue and use it for something specific.
I hope that you found this useful!








July 14th, 2009 at 4:55 pm
The File Extension DMG file could be described as the Apple version of a .EXE (Exectuble File) and replaced Mac OS Xs .IMG format. As a disk image format the file maps a folder tree and its contents allowing the file to be virtually mounted on the computer as if it were a real drive. However the File Extension DMG format can be mounted as a drive irrespective of whether it is an image of an existing device or not, and is used to distribute Apple software.
March 4th, 2010 at 8:37 pm
Hello, I came across this blog article while searching for help with JavaScript. I’ve recently switched browsers from Safari to Firefox 3.2. Now I seem to have a problem with loading JavaScript. Everytime I go on a page that requires Javascript, the site freezes and I get a “runtime error javascript.JSException: Unknown name”. I cannot seem to find out how to fix it. Any aid is very appreciated! Thanks
June 10th, 2010 at 3:55 am
Thank you, this helped me, but because split function is depricated now, i suggest the solution which is useful for both file names and urls:
function stripExtension($filename = “”) {
if (!empty($filename)) {
$filename = strtolower($filename);
$extArray = explode(“.”, $filename);
$extension = “”;
foreach ($extArray as $extension);
return $extension;
} else {
return false;
}
}
August 25th, 2010 at 7:48 am
This might be easier???
$fileinfo = pathinfo(‘path/to/filename.pdf’);
$fileinfo['basename']; // Get file basename (returns eg. ‘filename.pdf’)
$fileinfo['extension']; // Get file extension (returns eg. ‘pdf’)
$fileinfo['filename']; // Get file name (returns eg. ‘filename’)