Tuesday, January 12, 2010

How To Find File Extension Using PHP?

Find the file extension using php

If you wanted to rename a file upload you would still need to keep the extension. We can use these functions to find out the file extensions. Once found it can be appended to the end of a random number or a timestamp (or other naming system you choose) to use as the file name. There are several ways determine a file extension using PHP.These methods will return any file extension no matter how long or short it is.

First Method


First is using the combination of strrpos() and substr() function like this :For example, if $fileName is sample.jpg then strrpos($fileName, '.') will return the last location a dot character in $fileName. So substr($fileName, strrpos($fileName, '.') + 1) equals to substr($fileName, 16) which return 'jpg'.
<?php
echo "<br> First method</br>";
$fileName = "sample.php";
$ext = substr($fileName, strrpos($fileName, '.') + 1);
echo $ext;
?>

Second Method


The second is using strrchr() and substr() :

$ext = substr(strrchr($fileName, '.'), 1);

<?
echo "<br>Second method</br>";
echo $ext = substr(strrchr($fileName, '.'), 1);
?>

strrchr($fileName) returns '.jpg' so substr(strrchr($fileName, '.'), 1) equals to substr('.jpg', 1) which returns 'jpg'

Third Method

Using the pathinfo function we can get the file path details. It returns the extension also.
<?
echo "<br>Third method</br>";
// get the path info
$fileinfo = pathinfo($fileName);
// will show the extension
echo $fileinfo['extension'];
?>

Fourth Method

<?
echo "<br>Fourth method</br>";
$filename = strtolower($fileName) ;
$exts = split("[/\\.]", $filename) ;
$n = count($exts)-1;
$exts = $exts[$n];
echo $exts;
?>
Basically what the code is doing is first using strtolower to change the extension (and the whole file name) into lower case, just to keep it clean. Next we are splitting the filename into an array using split. By splitting it at the [.] the extension will be the last element in the array, which we then return.

Fifth Method

<?
echo "<br>Fifth method</br>";
$fileDet = explode('.', $filename);
echo end($fileDet);
?>