How to get file extension using PHP

Post Reply
User avatar
Saman
Lieutenant Colonel
Lieutenant Colonel
Posts: 828
Joined: Fri Jul 31, 2009 10:32 pm
Location: Mount Lavinia

How to get file extension using PHP

Post by Saman » Thu Apr 22, 2010 2:04 am

There are several ways determine a file extension using PHP. First is using the combination of strrpos() and substr() function like this :

Code: Select all

$ext = substr($fileName, strrpos($fileName, '.') + 1); 
For example, if $fileName is my-new-house.jpg then strrpos($fileName, '.') will return the last location a dot character in $fileName which is 15. So substr($fileName, strrpos($fileName, '.') + 1) equals to substr($fileName, 16) which return 'jpg'

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

Code: Select all

$ext = substr(strrchr($fileName, '.'), 1); 
strrchr($fileName) returns '.jpg' so substr(strrchr($fileName, '.'), 1) equals to substr('.jpg', 1) which returns 'jpg'
Post Reply

Return to “PHP & MySQL”