Asked 7 years ago
21 Oct 2016
Views 3921
sachin

sachin posted

how to get extension from the filename in PHP ?

how to get extension from the filename in php
i had some code

$file='display.txt';
$fileinfo=explode(".",$file);
if($fileinfo[1]=='txt'){
     echo file_get_contents($file);
}


i made this code my own but not sure it is good way to find extension from the file in php
Mitul Dabhi

Mitul Dabhi
answered Nov 30 '-1 00:00

use pathinfo function to get metadata(info about the file) of file

$file='display.txt';
$fileinfo=pathinfo($file);
if($fileinfo['extension']=='txt'){
     echo file_get_contents($file);
}

or you can use

$file='display.txt';
$fileext=pathinfo($file,PATHINFO_EXTENSION );
if($fileext=='txt'){
     echo file_get_contents($file);
}


function pathinfo give you array contain with directory,basename(filename with extension),extension and filename with out exension

$file='www/display.txt';
$fileinfo=pathinfo($file);
print_r($fileinfo);

give you output

Array ( [dirname] => www [basename] => display.txt [extension] => txt [filename] => display ) 



function pathinfo should have first argument filename and second will be option of output . you can pass second argument one of PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION or PATHINFO_FILENAME.
if you pass PATHINFO_EXTENSION second argument in pathinfo function you will get extension as string not array
so


$file='www/display.txt';
$fileinfo=pathinfo($file,PATHINFO_EXTENSION );
echo($fileinfo);

give you output

txt 
pathinfo($path,4);also return extension PATHINFO_EXTENSION is equal to 4 - Phpworker  
Oct 21 '16 13:52
shyam

shyam
answered Nov 30 '-1 00:00

to get file extension from filename at PHP . you can use strpos and substr to get file extension as well


$file='file.txt';
$start= strpos($file,".");
echo substr($file, $start );


start to find the string from "." by substr .

if you have filename with two dot , than also it works and find the file extension from filename for PHP


$file='file.tar.giz';
$start= strpos($file,".");
echo substr($file, $start );



Mahesh Radadiya

Mahesh Radadiya
answered Nov 30 '-1 00:00

pathinfo is not good to use get extension
suppose if you have path contain two or more dot (.) than expected result will raise

$file="www/data.tar.giz";
echo pathinfo($file,PATHINFO_EXTENSION );// will result "giz" 


so i suggest another function

$file="www/data.tar.giz";
echo $extension = substr($file,strpos($file, ".")+1, strlen($file));// will result "tar.giz"


if you want only last extension like giz

$file="www/data.tar.giz";
echo $extension = substr(strrchr($file, "."), 1);// will result "giz"


its very fast and good to use
Post Answer