PHP MySQL Tutorial
Learn PHP and MySQL

Determine a File Extension Using PHP

100% of people found this useful
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'

Recent Comments

By: Dan Posted on 05-06-2009 1:55 PM

Very good & useful

By: Dan Posted on 05-06-2009 1:55 PM

Very good & useful

By: wlabesamis Posted on 05-28-2009 1:41 AM

try this one.

<?php

/*** example usage ***/

$filename = 'filename.blah.txt';

/*** get the path info ***/

$info = pathinfo($filename);

/*** show the extension ***/

echo $info['extenstion'];

?>

By: crivion Posted on 05-28-2009 2:24 PM

way more easier,

print end(explode(".", $ext);

By: wlabesamis Posted on 05-28-2009 7:54 PM

i think there's a bug on your code. what if there is no file extesion?

print end(explode(".",'sample.txt')); //output is txt

print end(explode(".",'sample')); //output is sample

the output is correct if the file have an extension.

Powered by Community Server (Non-Commercial Edition), by Telligent Systems