This is a question you can read everywhere on the web with various answers:
$ext = end(explode(\'.\', $filename));
$ext = substr(strrchr($filename, \'.\'), 1
A quick fix would be something like this.
// Exploding the file based on the . operator
$file_ext = explode('.', $filename);
// Count taken (if more than one . exist; files like abc.fff.2013.pdf
$file_ext_count = count($file_ext);
// Minus 1 to make the offset correct
$cnt = $file_ext_count - 1;
// The variable will have a value pdf as per the sample file name mentioned above.
$file_extension = $file_ext[$cnt];
You can get all file extensions in a particular folder and do operations with a specific file extension:
<?php
$files = glob("abc/*.*"); // abc is the folder all files inside folder
//print_r($files);
//echo count($files);
for($i=0; $i<count($files); $i++):
$extension = pathinfo($files[$i], PATHINFO_EXTENSION);
$ext[] = $extension;
// Do operation for particular extension type
if($extension=='html'){
// Do operation
}
endfor;
print_r($ext);
?>
Use substr($path, strrpos($path,'.')+1);
. It is the fastest method of all compares.
@Kurt Zhong already answered.
Let's check the comparative result here: https://eval.in/661574
This will work
$ext = pathinfo($filename, PATHINFO_EXTENSION);
The simplest way to get file extension in PHP is to use PHP's built-in function pathinfo.
$file_ext = pathinfo('your_file_name_here', PATHINFO_EXTENSION);
echo ($file_ext); // The output should be the extension of the file e.g., png, gif, or html
IMO, this is the best way if you have filenames like name.name.name.ext (ugly, but it sometimes happens):
$ext = explode('.', $filename); // Explode the string
$ext_len = count($ext) - 1; // Count the array -1 (because count() starts from 1)
$my_ext = $ext[$ext_len]; // Get the last entry of the array
echo $my_ext;