Pete
Pete

Reputation:

Get the file extension (basename?)

If I have a code like this:

$file = basename($filename); 

How do I get the file extension of $file? The variable $file could contain any kind of file, like index.php or test.jpeg.

Upvotes: 14

Views: 18432

Answers (2)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179219

pathinfo($filename, PATHINFO_EXTENSION);

Upvotes: 6

cletus
cletus

Reputation: 625447

Use the pathinfo() function:

$path_parts = pathinfo('/www/htdocs/index.html');

echo $path_parts['dirname'], "\n";
echo $path_parts['basename'], "\n";
echo $path_parts['extension'], "\n";
echo $path_parts['filename'], "\n";

or simply:

echo pathinfo($file, PATHINFO_EXTENSION);

You can of course look for the last "." in the filename and get everything after (relatively easy) but why reinvent the wheel?

Upvotes: 42

Related Questions