How do I get (extract) a file extension in PHP?


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];


However, there is always "the best way" and it should be on Stack Overflow.

1/25/2019 5:58:06 AM

Accepted Answer

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 and built-in. pathinfo() can give you other information, such as canonical path, depending on the constant you pass to it.

Remember that if you want to be able to deal with non ASCII characters, you need to set the locale first. E.G:


Also, note this doesn't take into consideration the file content or mime-type, you only get the extension. But it's what you asked for.

Lastly, note that this works only for a file path, not a URL resources path, which is covered using PARSE_URL.


11/12/2018 3:29:47 PM


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

echo $path_info['extension']; // "bill"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow