DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get File Extension

10.04.2006
| 194380 views |
  • submit to reddit
        
function file_extension($filename)
{
    $path_info = pathinfo($filename);
    return $path_info['extension'];
}
    

Comments

Snippets Manager replied on Fri, 2010/12/10 - 4:25pm

Can this code be used to find a file extension?

Snippets Manager replied on Thu, 2012/01/19 - 11:29am

What I use: $filename = "my-directory/my-file-name.php" $extension = pathinfo($filename, PATHINFO_EXTENSION); see http://cowburn.info/2008/01/13/get-file-extension-comparison/

Snippets Manager replied on Tue, 2009/09/08 - 1:12pm

visit http://www.itbugz.com/viewtopic.php?f=6&t=894&p=942#p942 you will get resukt

Snippets Manager replied on Sat, 2009/09/05 - 10:30am

to albert006, FlashPack and expertseries: - notice a NICE ERROR which will happens when given filename wont have an extension and somewhere in the path to tested file IS a "dot" in dirname. For example "/etc/init.d/README" on Ubuntu will return a NICE "d/README" extension. Thus I advice you to stick to the original file_extension($filename) using pathinfo($filename).

Snippets Manager replied on Mon, 2009/04/13 - 8:51pm

expertseries, sorry, but your answer is why people make fun of PHP developers. The solution stancell posted is much more readable than yours. Why dick around with the details of array pointer semantics when there's a library function that does exactly what you need, and has been tested much more thoroughly?

Snippets Manager replied on Mon, 2012/05/07 - 2:29pm

FlashPack, notice the 'end' function call? It advances array's internal pointer to the last element, and returns its value.

Snippets Manager replied on Fri, 2008/12/05 - 6:41pm

function file_extension($filename) { return end(explode(".", $filename)); } this method won't work if the file name has many dots

Snippets Manager replied on Sat, 2006/11/04 - 6:41am

Not faster, but slower in 0.5 times.

Snippets Manager replied on Mon, 2006/10/16 - 6:57pm

Sorry I didn't use code formatting: function file_extension($filename) { return end(explode(".", $filename)); }

Snippets Manager replied on Mon, 2006/10/16 - 6:57pm

Maybe faster: function file_extension($filename) { return end(explode(".", $filename)); }