PHP Function To Get A File Extension From A String

By on  

Getting the file extension from a PHP string can be very important in validating a file or file upload. I've written a simple PHP function to retrieve a file extension from a string.

The Code

function get_file_extension($file_name) {
	return substr(strrchr($file_name,'.'),1);

This simple method of file extension retrieval should be reused throughout your code.

Track.js Error Reporting

Recent Features

  • CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

  • CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

  • Jack Rugile’s Favorite CodePen Demos

    CodePen is an amazing source of inspiration for code and design. I am blown away every day by the demos users create. As you'll see below, I have an affinity toward things that move. It was difficult to narrow down my favorites, but here they are!...

  • Adding Events to Adding Events in MooTools

    Note: This post has been updated. One of my huge web peeves is when an element has click events attached to it but the element doesn't sport the "pointer" cursor. I mean how the hell is the user supposed to know they can/should click on...


  1. This looks really useful, thanks.

  2. Why reinvent the wheel? We have good ol’ pathinfo() :

    [dirname] => .
    [basename] => some.file.extension
    [extension] => extension
    [filename] => some.file

  3. I came up with this snippet to get the file extension as well, using array functions:

  4. … and it got cut out. Here’s the function, without tags:

    function get_file_extension($file_name) {
       return end(explode('.',$file_name));
  5. As mentioned by ochronus the following code does the exact same thing:

    $file = '/tmp/test.php'; 
    echo pathinfo($file, PATHINFO_EXTENSION);
  6. or we can do it via end(explode('.', "filename.ext")); easily

  7. Rafieldex

    File extension from path:

    function f_extension($fn){
    return $ext;
    $extesnion=f_extension("files/file.jpg"); // returns jpg

    Try & enjoy!

  8. Jorge

    What happens when you try to get the extension of “/etc/init.d/README” with the explode method?

    Just use the pathinfo().

    • rafieldex

      Oh come on…i wrote this post quickly.

      function f_extension($fn){
        if (strpos($str[($len-1)],'.') === False) return False; // Has not .
      return $ext;
    • Sky

      lol. Why?!
      Just use the pathinfo()!!!!!!

      Do you re-write every function that’s in PHP, including stuff like mktime() ????????

    • jack

      I don’t like rhetoric. You asked why? Could be many reasons. You just need some imagination.

      – Didn’t know about pathinfo (could be many reasons for this. New to PHP, came frmo a different language, simply has a knowledge gap)
      – Did not know what pathinfo could do (it’s not well documented)
      – Wrote the routine just for fun to improve programming skills (not used in actual project)

  9. @Jorge: Either way works, and it just ends up being a matter of preference. You have to consider how this function will usually be used on a web application; it will be grabbing the extension and making sure it’s an allowed extension for upload. Thus, the explode method would return something that doesn’t match a valid extension (like your README example), and the file upload would get declined.

    If you’re building a file explorer on the web, sure, use pathinfo(); that’s common sense. If you’re building a web app that takes uploads, then I can’t imagine the explode method would not be faster than pathinfo.

  10. Thanks for sharing !

  11. sumit

    @crivion: please explain it with example

  12. DaveDisaster

    I’ve run a bunch of microtime() tests, and almost every time pathinfo() is the fastest, by a healthy margin over end/explode. substr/strrchr seems to vary somewhere in the middle.

  13. There are many way to get file extension. For me, I use
    end(explode('.', $_FILES['fileupload']['name']));
    I think this is easy to understand code from it.

  14. // gif image uploaded
    if (isset($_FILES[‘file’])) {
    $file_extension =$_FILES[‘file’][‘extension’] ;
    $extension = substr(“$file_extension”, 6); // remove the image/ and the gif extension remains.
    echo $extension // return gif

  15. sudhir

    Thanks , IT is really very user full.

  16. I always prefer php code functions eg.

    $file_extension=pathinfo($filename, PATHINFO_EXTENSION);

  17. I found this post from Google, and though “wow, what a simple answer.” I then read the comments suggesting alternative methods and gave those a try as well. They all work of course, but I wanted to know what worked *better*, so I benchmarked them. The following is how long it took my server to run each method 1 million times on the string: ‘/var/www/thisisatest.1.2.18.min.js’

    Substr: 0.8037 seconds
    Pathinfo: 1.95027 seconds
    Explode: 2.35024 seconds

    Clearly, the method you posted smoked the competition. I will be using it. Thank you for posting this!

  18. jay

    if your doin comparison checks on file ext try

    return strtolower(substr(strrchr($file_name,’.’),1));

  19. While end(explode(‘.’,$file_name)); is indeed immediately intuitive to even an newbie, you could really help a programmer take a step forward by introducing him/her to the more useful pathinfo($path, $options);

    In addition pathinfo does what it says, so is automatically the winner of the Best Practice award.

    This comes from an advanced php’er who has never used the function until I seen it mentioned here. So thanks to David and all of you for your cross-examination

  20. jack

    All the folks complaining about not using pathinfo()….There are times you do not want to use pathinfo(). For instance, when listing filenames on Amazon S3 without going to the trouble of downloading the file onto your server. You don’t have the actual file, so you may just want to parse the string…

    • Sky

      Pathinfo accepts strings as a variable,
      so your point is invalid.

      You ALWAYS should use existing PHP function whenever possible.
      Just like in the HTML – if you create a table: use table element, don’t make up one from divs.

  21. jack

    @Sky A sincere thanks for the info, but the mini-lecture was not necessary. I’m quite aware that in normal cases the wheel should not be invented. I’m a software engineer who simply comes from a C++ and Objective-C background and don’t know PHP well. PHP is a rather badly designed and unpredictable language, the man page on pathinfo is of no great help.

  22. jack

    Sky: A sincere thanks for the info, but the following lecture was not necessary. I’m quite aware that in normal cases the wheel should not be invented. I’m a software engineer who simply comes from a C++ and Objective-C background and doesn’t know PHP well. IMHO PHP is a rather badly designed and unpredictable language, and the man page on pathinfo is rather poor. Paths are PHP are *necessarily* strings with no level of abstraction over it. The manual should have documented whether it requires an actual path or not.

  23. What if you are handling a url and its possible that we have a http://imgur.com/blablabla.jpg?x=15

    Pretty much would never happen but good code will deal with odd data.

  24. LeePro

    all methods fail if path has query or hash:
    $filename = “mypic.gif?see=me#now”;

  25. Yay, pathinfo() Do The Best :D

  26. Look Code This , This Code Part Of Symfony Dependency Injection Loader

    public function supports($resource, $type = null) {
       return is_string($resource) && 'php' === pathinfo($resource, PATHINFO_EXTENSION);
  27. Tayo
    $filename = 'mypic.gif';
    $ext = pathinfo($filename, PATHINFO_EXTENSION);

    This is faster based on http://www.cowburn.info/2008/01/13/get-file-extension-comparison/

  28. Thanks. useful

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OSCON Portland:  Conference  Discount!

    O'Reilly puts on the best web industry conferences in the world.  These conferences include Fluent Conference, Velocity Conference, and the upcoming OSCON in Portland, Oregon from July 20-24.  Open Source Convention (OSCON) is a conference that focuses specifically on open source developers and the tools and possibilities...

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...