Friday, June 1, 2012

How to extract a file extension in PHP?


This is a question you can read everywhere on the web with various answers :




$ext = end(explode('.', $filename));
$ext = substr(strrchr($filename, '.'), 1);
$ext = substr($filename, strrpos($filename, '.') + 1);
$ext = preg_replace('/^.*\.([^.]+)$/D', '$1', $filename);
$exts = split("[/\\.]", $filename);
$n = count($exts)-1;
$ext = $exts[$n];



etc.



However, there is always "the best way" and it should be on stackoverflow.


Source: Tips4all

4 comments:

  1. People from other scripting languages always think theirs is better because they have a built in function to do that and not PHP (I am looking at pythonistas right now :-)).

    In fact, it does exist, but few people know it. Meet pathinfo :

    $ext = pathinfo($filename, PATHINFO_EXTENSION);


    This is fast, efficient, reliable and built in. Pathinfo can give you others info, such as canonical path, regarding to the constant you pass to it.

    Enjoy

    ReplyDelete
  2. pathinfo - http://uk.php.net/manual/en/function.pathinfo.php

    An example...

    $path_info = pathinfo('/foo/bar/baz.bill');

    echo $path_info['extension']; // "bill"

    ReplyDelete
  3. E-satis response is the correct way to determine the file extension.

    Alternatively, instead of relying on a files extension, you could use the fileinfo (http://us2.php.net/fileinfo) to determine the files MIME type.

    Here's a simplified example of processing an image uploaded by a user:

    // Code assumes necessary extensions are installed and a successful file upload has already occurred

    // Create a FileInfo object
    $finfo = new FileInfo(null, '/path/to/magic/file');

    // Determine the MIME type of the uploaded file
    switch ($finfo->file($_FILES['image']['tmp_name'], FILEINFO_MIME) {
    case 'image/jpg':
    $im = imagecreatefromjpeg($_FILES['image']['tmp_name']);
    break;

    case 'image/png':
    $im = imagecreatefrompng($_FILES['image']['tmp_name']);
    break;

    case 'image/gif':
    $im = imagecreatefromgif($_FILES['image']['tmp_name']);
    break;
    }

    ReplyDelete
  4. You only need:
    Example:


    strrchr('image.two.jpg', '.')


    You get -> .jpg!

    ReplyDelete