Wednesday, February 9, 2011

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.

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

    An example...

    $path_info = pathinfo('/foo/bar/baz.bill');
    
    echo $path_info['extension']; // "bill"
    
    vaske : This one is "the best way"
  • 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

    J-P : Why didn't you just put the answer in the question!?
    e-satis : Because it's written is the overflow FAQ do it this way.
    Mark Biek : I wish I could vote this up twice. I can't tell you how much code I've been able to replace using pathinfo
    e-satis : So do I. That's why I put it here !
    From e-satis
  • 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;
    }
    
    From Toxygene

0 comments:

Post a Comment