13

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.

PeeHaa
  • 71,436
  • 58
  • 190
  • 262

2 Answers2

41

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?

cletus
  • 616,129
  • 168
  • 910
  • 942
5
pathinfo($filename, PATHINFO_EXTENSION);
IonuČ› G. Stan
  • 176,118
  • 18
  • 189
  • 202