Determine a File Extension Using PHP

free php tutorials, php classes, php utilities, free tools

There are several mehods to get file extension using PHP. First is using the combination of strrpos() and substr() function like this :

$filename = 'mypic.gif';
$ext = substr($filename, strrpos($filename, '.') + 1);

For example, if $filename is mypic.gif 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 'gif'

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

$filename = 'mypic.gif';
$ext = substr(strrchr($filename, '.'), 1);
strrchr($filename) returns '.gif' so substr(strrchr($filename, '.'), 1) equals to substr('.gif', 1) which returns 'gif'

We can also get file extension using these methods.

$filename = 'mypic.gif';
// 1. The "explode/end" approach
$ext = end(explode('.', $filename));

// 2. The "strrchr" approach
$ext = substr(strrchr($filename, '.'), 1);

// 3. The "preg_replace" approach
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);

Bookmark This Page