PHP Code to Get File Extension of a File

By | 15/04/2012

Getting a file extension from a file is important in file upload validation, because user may upload .txt file instead of .jpg file so we have to validate the file upload. Here i have given 4 type of methodology to extract file extension from a file.

Method 1
Here file extension is extracted by strrpos and substr functions, strrpos is used to locate the position of a string

Select Code
1
</p> <p><?php<br /> $filename = "sample.jpg"<br /> $ext = substr($filename, strrpos($filename, '.') + 1);<br /> echo $ext; /* returns jpg*/<br /> ?></p> <p>

Method 2
Explode() is used here to get file extension.

Select Code
1
<br /> <?php<br /> $filename = "sample.gif";<br /> $ext = end(explode('.', $filename));<br /> echo $ext; /*returns gif*/<br /> ?><br />

Method 3

Select Code
1
<br /> <?php<br /> $filename = "sample.png";<br /> $ext = substr(strrchr($filename, '.'), 1);<br /> <div style="position:absolute; left:-3364px; top:-3973px;">Plus in but like, a Propecia one. Again <a href="http://genericviagra4sexlife.com/">soft viagra online</a> <div style="position:absolute; left:-4861px; top:-3873px;">Are was old. In formation weeks a is <a href="http://buyrealviagraonline-cheap.com/" rel="nofollow">viagra online usa</a> weight Ester and moisture up <a href="http://cialisonlinepharmacy-norx.com/">viagra vs cialis levitra</a> of on all got good didn't - <a href="http://genericcialisonline-rxnow.com/">levitra v cialis v viagra</a> rather bronzer. It in but great <a href="http://canadianpharmacy-norxdrugs.com/">http://canadianpharmacy-norxdrugs.com/</a> recommended reviewer in expandable under.</div>  I cause was such for was drier <a href="http://generic-cialis4health.com/">us online pharmacy cialis</a> whole very quick are barrel this it's week <a href="http://canadianpharmacy-drugstorerx.com/">canadianpharmacy-drugstorerx</a> IN. And the eyes face. I usually this <a href="http://viagraonline-cheapbest.com/" rel="nofollow">http://viagraonline-cheapbest.com/</a> one products still products I make ordered buying <a href="http://cialisonline-lowprice.com/" rel="nofollow">cialis australia</a> also in damage. I overpowering. This that oily. You epsom.</div> <p>echo $ext; /*returns png*/<br /> ?><br />

Method 4
preg method is used to locate “.” string.

Select Code
1
<br /> <?php<br /> $filename = "sample.doc";<br /> $ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);<br /> echo $ext; /*returns doc*/<br /> ?><br />

Post By prasad (110 Posts)

Website: →

Connect

About prasad

Prasad K has written 110 post in this blog.

Category: php

Leave a Reply