Tuesday 29 November 2011

The Right Way to Get a File Extension in PHP

I made a recent search on retrieving file extensions in PHP.

I found out that a lot have been re-inventing the wheel. They have been creating code for functionality that PHP already has. This is one example of re-inventing the wheel

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


Another example was this:

function file_extension($filename)
{
return end(explode(".", $filename));
}


PHP already has a function that does the same thing and more.

Welcome, pathinfo.

$file_path = pathinfo('/www/htdocs/your_image.jpg');
echo "$file_path ['dirname']\n";
echo "$file_path ['basename']\n";
echo "$file_path ['extension']\n";
echo "$file_path ['filename']\n"; // only in PHP 5.2+


// Output
/www/htdocs
your_image.jpg
jpg
your_image


A much easier way to use the constants:
[PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME]

PATHINFO_DIRNAME - the directory
PATHINFO_BASENAME - the file name
PATHINFO_EXTENSION - the extension
PATHINFO_FILENAME - the filename without the extension

echo pathinfo('/www/htdocs/your_image.jpg', PATHINFO_EXTENSION);

// Output

jpg