How to get a file extension

by Arnold Daniels on 05/31/2008

How to get a file extension in PHP:

1
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$ext = pathinfo($file_name, PATHINFO_EXTENSION);

How to get a file extension in Perl:

1
my $ext = ($file_name =~ m/([^.]+)$/)[0];
my $ext = ($file_name =~ m/([^.]+)$/)[0];

How to get a file extension in Ruby:

1
ext = File.extname(file_name)
ext = File.extname(file_name)

How to get a file extension in Bash:

ext=${file_name##*.}
name=${file_name%.*}

How to get a file extension in Python (thanks to Jensen):

import os
ext = os.path.splitext(file_name)[1]

How to get a file extension in JavaScript:

1
var ext = /\.(\w+)$/.exec(file_name)[1]
var ext = /\.(\w+)$/.exec(file_name)[1]


Got more? Please post a comment.

Arnold Daniels

I've spend a big part of my life behind a computer, learning about databases (MySQL), programming (PHP) and system administration (Linux). Currently I playing with HTML5, jquery and node.js.

E-mailTwitterLinkedInGithubGittip

There are 28 comments in this article:

  1. 31 May 2008Philip Olson says:

    It would be interesting to provide code with the following two examples:

    foo.tgz
    foo.tar.gz

    This would essentially require two snippets for each language… depending on what the user wanted to do.

    ReplyReply
  2. 31 May 2008Jensen says:

    Python:
    import os
    ext = os.path.splitext(file_name)[1]

    If “file_name” is “my.file.txt” the “ext” variable will contain “.txt”.

    ReplyReply
  3. 31 May 2008Arnold Daniels says:

    For .tar.gz, only gz is seen as the extension. If necessary, you need to make an exception for tar.gz.

    Also you might want to say that this it should only give an extension when the filename has a dot, eg README has no extension. This isn’t done correctly with the Perl and bash example.

    With a regex it would be

    /(?< =\.)(tar\.gz|[^./\/])$/
    ReplyReply
  4. 31 May 2008Gareth Heyes says:

    Javascript:-

    /[^.]{1,3}$/.exec(‘.testest.jpg’)

    ReplyReply
  5. 31 May 2008Brutos says:

    Windows commandline:
    echo %~x1

    ReplyReply
  6. 31 May 2008Bruce Weirdan says:

    @Gareth Heyes:
    extension is usually defined as last part after a dot (not limited to three characters). So it would be
    /[^.]+$/.exec(‘filename.with.extension’) // here extension is ‘extension’

    @Arnold:
    Your comment form does not work with javascript off.

    ReplyReply
  7. 1 June 2008Jeremy Privett says:

    C# –

    FileInfo f = new FileInfo(“test.txt”);
    string ext = f.Extension; # ext = txt

    ReplyReply
  8. 1 June 2008Alan Knowles says:

    D
    char[] ext =std.path.getExt(fnam)

    gtkds (javascript)
    var ext= Path.getExt(fname)

    ReplyReply
  9. 1 June 2008ace says:

    // what about writing classes/functions for common operations?

    $ext = File::ext($filename);

    // included file

    class File {
    static function ext($filename)
    {
    return pathinfo($file_name, PATHINFO_EXTENSION);
    }
    }

    ReplyReply
  10. 5 June 2008gi_gio says:

    Hi Arnold, sorry if I’m posting here, but I did not found another way to contact you.
    I’ve just read a message that you posted on the forum of the mysql website.
    You wrote that you’ve got a php lib based on fast regexp that can parse a mysql query string to retrieve information like: operation (INSERT, UPDATE..), tables, fields… and so on.
    I was looking for such a library, can you help me, please?

    Thank you in advance!

    ReplyReply
  11. 10 June 2008rx8wej says:

    in C# (alternative):

    string path = “C:\file.txt”;
    string ext = path.SubString(path.LastIndexOf(“.”) + 1);

    ReplyReply
  12. 26 June 2008Henk says:

    @ ace for his ‘making it a class’ business, in a proper OO thingy, you’d more likely see a structure like

    $file = new File(‘somefile.txt’);
    echo $file->GetExtension();

    since ‘putting it into a class’, as described by you, is basically just ‘wrapping the php function into another function, with the additional overhead of putting it into a class in order to simulate namespaces’.

    ReplyReply
  13. 21 December 2008private credit record score in calgary alberta says:

    private credit record score in calgary alberta…

    redouble?missed,leafed!hatred,…

  14. 30 December 2008diyopatino says:

    my ($ext) = $file_name =~ m/([^.]+$)/;

    ReplyReply
  15. 28 February 2009Maelvon says:

    In a CGI with perl, I got the extension with:

    my $ext = ($file_name =~ m/.*\.(.+)$/)[0];

    ReplyReply
  16. 19 June 2009Muhammad Azhar says:

    Thanks for ur kind help.

    ReplyReply
  17. 30 September 2009NoMoreFreeBeer_Ban_Inbev_AnheuserBusch says:

    PHP
    Keep it simple!
    Use explode!

    $extension = end(explode(‘.’, $file));

    Returns everything after the last “.”.

    ReplyReply
  18. 30 September 2009Arnold Daniels says:

    Using explode won’t give you the wanted result:

    $file = “/etc/passwd”;
    $extension = end(explode(’.’, $file));
    echo $extension; // Outputs ‘/etc/passwd’

    For PHP use pathinfo() as described in the above article.

    ReplyReply
  19. 30 September 2009Sandor says:

    end(explode works quite well as posted. Without the “end” you will get the undesired result mentioned above.

    Here is some info on explode and also has an example of the end(explode method that shows that it does work quite well.

    http://us3.php.net/manual/en/function.explode.php#87049

    My expertise quite limited. Been writing in php off and on only about 5 years now. The explode method works for me though in many ways.

    The goal was to return the extension of a file name. Just like the examples at the top of the page here. Right?

    That explode example will do just that. I use it all the time in my snippets. Efficiency is relative to the end app I guess though.

    $file = “someimage.jpg”; //or even some.image.jpg

    $extension = end(explode(‘.’, $file));

    outputs jpg

    // It does everything after the last ‘.’

    I was told by many it is the most efficient way to grab a file name extension with php. If there is a way that uses less resources, I will use it instead.

    Using pathinfo:

    $path_parts = pathinfo(‘/www/index.html’);

    Enables me to:

    echo $path_parts['dirname'], “\n”;
    echo $path_parts['basename'], “\n”;
    echo $path_parts['extension'], “\n”;
    echo $path_parts['filename'], “\n”;

    I “think” pathinfo uses more “resources” than just getting the specific result as I did in the explode example. I could be very wrong. If someone could prove one is method “better” that the other, I will use the better one for sure! I also become concerned about security. The explode method exposes more by far. But it is php. ;-)

    Now, in cases where you need to break a file name up, do some pattern matching or directory creation then reconstruct it all later for some reason or another, pathinfo has everything you need all ready and waiting. I use it for that frequently. But, when I don’t, I use the explode method to grab parts of a string or file. When I actually write apps in php that is..

    Great topic. So many ways to perform a seemingly simple task. But, just because it is simple does not mean it is easy!

    Thanks guys!

    ReplyReply
  20. 1 October 2009Arnold Daniels says:

    Sandor: Thanks for you input, but please have a closer look at my comment.

    Using explode will not work correctly if the file does not have an extension. It will work for ‘/var/www/someimage.jpg’, but not for ‘/etc/group’. Please execute the code and see for your self.

    Please also note the PATHINFO_% constants. You don’t need to get the whole array and than get the extension part from that.

    This is most definitely faster than doing an explode + end, since you don’t need to create an array, which is a relative expensive operation.

    define('LOOP', 10000);
    
    function wasteTime() {
        for ($i=0; $i
    

    screenshot-php-profile-q-demos-benchmark-extensionphp-zend-studio

    I made a error in the benchmark code. Updated the profiling results

    ReplyReply

  21. 1 October 2009Sandor says:

    Excellent, thank you… Your input here forces me to test all my snippets in Zend studio. What’s the use of having it if I don’t use it!

    As far as the security holes when no extension is present (and other possibilities), I was sanitizing before I got to explode. Chalking up some more time on to the explode method.

    Thanks again!

    ReplyReply
  22. 1 October 2009Sandor says:

    So in PERL, would using

    $string= do some /stuff $ENV(‘PATH_INFO’)/g;

    be a better/safer way to grab an extension or even a whole ?query. Replacing the need for a query and even avoiding loading a perl module like CGI. Hence more security and a so on like:

    #!/usr/bin/perl -Tw
    use strict;
    use warnings;
    BEGIN{$SIG{__DIE__} = \&FatalErr} #my dies go to a sub#
    $ENV{PATH} = “bin:/usr/bin”;
    delete ($ENV{qw(IFS CDPATH BASH_ENV ENV)});
    my $string=”";
    $string= do some /stuff with $ENV(‘PATH_INFO’) /here/;
    #sanitize $string here
    #split it up as needed..

    All vars are now ready…

    Prob a one liner that can break up the whole deal after taint.

    That was just a quick type so, don’t take it literally, just a concept.

    I have a PERL sub I am working on that I would like to share here for help in developing it. Everyone who serves up images could use it when done. I will find the proper category to post it here when I clean it up a bit..

    ReplyReply
  23. 4 December 2009Cully Larson says:

    For Perl, you forgot the parens around your match group:

    my $ext = ($file_name =~ m/([^.]+)$/)[0];

    ReplyReply
  24. 21 December 2009satan says:

    Thanks! This helped a lot!!

    ReplyReply
  25. 18 February 2010Nathan L Smith says:

    CommonJS:

    From http://wiki.commonjs.org/wiki/Filesystem/A, works on Narwhal:

    require(“file”).extension(fileName);

    ReplyReply
  26. 17 August 2011Extract sff for selected IDs into a child sff (version 2) « Open Source Pharmacist says:

    [...] sff for selected IDs into a child sff (version 2)I thank Peter Cock, Brad Chapman, and Arnold Daniels for the development of the second [...]

  27. 7 December 2011MRC says:

    If I’m not mistaken, this is valid for all the languages and cases…
    Reverse the string and parse it until the first dot.
    Sorry for not posting any examples, but my programming skills are limited.

    ReplyReply
  28. 29 August 2012anonymous says:

    It helped. Thanks.

    ReplyReply

Write a comment: