SiteCrafting Blah Blah Blog

Oct. 16, 2006 at 12:57pm

File Extensions

I've been using a fairly complicated function to grab the extension of an uploaded file. I have run across many instances where I have wanted to split up the file name from the file extension, or just find the file type. Since MIME types are not reliable enough for grabbing a true extension, I have been using this aforementioned function.
The following is a snippet of code that I had been using to retrieve the extension of a file:

<?php
$filename = 'image.jpg'; //name of file
$nombres = split('.', strtolower($filename));
$nombre_start = '';
for($k=0; $k<count($nombres)-1; $k++)
{
    $nombre_start .= $nombres[$k];   
}
$nombre_ext = $nombres[count($nombres)-1];
?>

However, there had to be an easier, cleaner way to get this information. So here is the code I came up with the following code for retrieving the extension of a file:

<?php
$filename = 'image.jpg'; //name of file
$ext = substr(strrchr($filename, "."), 1);
?>

In this case, printing $ext would give you "jpg".

Grabbing just the filename was a bit more involved, but still relied on the same principal:

<?php
$filename = 'image.jpg'; //name of file
$name = substr($filename, 0, strpos($filename,substr(strrchr($filename, "."), 0)));
?>

In this case, printing $name would give you "image".

Posted in Coding Techniques, PHP by Mark Neidlinger

Comments (5)

Kevin says:

Just function-ized this and put it to use on a project. Thanks Mark!

Here's 'da code:

function get_file_extension($filename) {
   return substr(strrchr($filename, "."), 1);
}
1 | Oct. 19, 2006 at 10:58am


I'm a regular expression fiend. I think your function is more processor-efficient, but if you wanted a "Swiss army knife" style function, a regular expression could be handy:


function filename_chop ($filename)
{
  return preg_match("/(.*)\.([^\.]*)$/", $filename, $matches) ? $matches : array($filename, $filename, NULL);
}

print_r(filename_chop("test.jpg"));
# Outputs:
# Array ( [0] => test.jpg [1] => test [2] => jpg )

2 | Left by Darren | Oct. 20, 2006 at 12:08pm


Kevin says:

That's right -- I remember putting those RegEx skills to good use on a couple projects while at PLU. Nice work.

(plus, I fixed the slashes issue in the comments -- w00t!)
3 | Oct. 20, 2006 at 1:21pm


Why not get the file name like this?

$splitzip = explode(".", $thisUploadArray['name']);
$zipName = $splitzip[0];
4 | Left by Brenton | Nov. 26, 2006 at 1:43am


Dave says:

Brenton -

I used that for awhile, but not all filenames only have one period in them. I name all of my classes like file.class.php. In this case, file.class is the name, and php is the extension.
5 | Nov. 30, 2006 at 1:40pm


Remember me
Name: Email: URL: Comment: *   No HTML, http:// will auto-link
* required    Comment Guidelines