This is a question you can read everywhere on the web with various answers:
$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1
You can try also this (it works on PHP 5.* and 7):
$info = new SplFileInfo('test.zip');
echo $info->getExtension(); // ----- Output -----> zip
Tip: it returns an empty string if the file doesn't have an extension
Although the "best way" is debatable, I believe this is the best way for a few reasons:
function getExt($path)
{
$basename = basename($path);
return substr($basename, strlen(explode('.', $basename)[0]) + 1);
}
tar.gz
You can try also this:
pathinfo(basename($_FILES["fileToUpload"]["name"]), PATHINFO_EXTENSION)
Low level calls need to be very fast so I thought it was worth some research. I tried a few methods (with various string lengths, extension lengths, multiple runs each), here's some reasonable ones:
function method1($s) {return preg_replace("/.*\./","",$s);} // edge case problem
function method2($s) {preg_match("/\.([^\.]+)$/",$s,$a);return $a[1];}
function method3($s) {$n = strrpos($s,"."); if($n===false) return "";return substr($s,$n+1);}
function method4($s) {$a = explode(".",$s);$n = count($a); if($n==1) return "";return $a[$n-1];}
function method5($s) {return pathinfo($s, PATHINFO_EXTENSION);}
Results
were not very surprising. Poor pathinfo
is (by far!) the slowest; even with the PATHINFO_EXTENSION
option, it looks like he's trying to parse the whole thing and then drop all unnecessary parts. On the other hand, the built-in strrpos
function is invented almost exactly for this job, takes no detours, so no wonder it performs a lot better than other applicants:
Original filename was: something.that.contains.dots.txt
Running 50 passes with 10000 iterations each
Minimum of measured times per pass:
Method 1: 312.6 mike (response: txt) // preg_replace
Method 2: 472.9 mike (response: txt) // preg_match
Method 3: 167.8 mike (response: txt) // strrpos
Method 4: 340.3 mike (response: txt) // explode
Method 5: 2311.1 mike (response: txt) // pathinfo <--------- poor fella
NOTE: the first method has a side effect: it returns the whole name when there's no extension. Surely it would make no sense to measure it with an additional strpos to avoid this behaviour.
This seems to be the Way of the Samurai:
function fileExtension($s) {
$n = strrpos($s,".");
return ($n===false) ? "" : substr($s,$n+1);
}