Page 1 of 1

How to get file extension using PHP

Posted: Thu Apr 22, 2010 2:04 am
by Saman
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'