views:

8958

answers:

3

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.

+9  A: 

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

An example...

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

echo $path_info['extension']; // "bill"
Adam Wright
This one is "the best way"
vaske
+45  A: 

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

e-satis
Why didn't you just put the answer in the question!?
J-P
Because it's written is the overflow FAQ do it this way.
e-satis
I wish I could vote this up twice. I can't tell you how much code I've been able to replace using pathinfo
Mark Biek
So do I. That's why I put it here !
e-satis
+3  A: 

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;
}
Toxygene