December 23, 2011

Determine a File Extension Using PHP

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

$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() :

$ext = substr(strrchr($fileName, ‘.’), 1);

strrchr($fileName) returns ‘.jpg’ so substr(strrchr($fileName, ‘.’), 1) equals to substr(‘.jpg’, 1) which returns ‘jpg’

Related posts:

  1. The Ecosystems Will Determine the Gadgets We Buy
  2. When You Need to Send Someone an Important File Really Fast..
  3. Super Bowl Ad Tweets Determine Brand Effectiveness
  4. Get your Office 2010 Upgrade Even if you are Late
  5. Copy a File’s Path to the Clipboard without any Registry Hacks!