Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get 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];

etc.

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

like image 670
e-satis Avatar asked Oct 06 '08 11:10

e-satis


People also ask

What extension PHP files have?

php extension.


4 Answers

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:

setlocale(LC_ALL,'en_US.UTF-8');

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.

Enjoy

like image 80
e-satis Avatar answered Nov 14 '22 00:11

e-satis


pathinfo()

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

echo $path_info['extension']; // "bill"
like image 44
Adam Wright Avatar answered Nov 14 '22 00:11

Adam Wright


Example URL: http://example.com/myfolder/sympony.mp3?a=1&b=2#XYZ

A) Don't use suggested unsafe PATHINFO:

pathinfo($url)['dirname']   🡺 'http://example.com/myfolder'
pathinfo($url)['basename']  🡺 'sympony.mp3?a=1&b=2#XYZ'         // <------- BAD !!
pathinfo($url)['extension'] 🡺 'mp3?a=1&b=2#XYZ'                 // <------- BAD !!
pathinfo($url)['filename']  🡺 'sympony'

B) Use PARSE_URL:

parse_url($url)['scheme']   🡺 'http'
parse_url($url)['host']     🡺 'example.com'
parse_url($url)['path']     🡺 '/myfolder/sympony.mp3'
parse_url($url)['query']    🡺 'aa=1&bb=2'
parse_url($url)['fragment'] 🡺 'XYZ'

BONUS: View all native PHP examples

like image 44
T.Todua Avatar answered Nov 14 '22 00:11

T.Todua


There is also SplFileInfo:

$file = new SplFileInfo($path);
$ext  = $file->getExtension();

Often you can write better code if you pass such an object around instead of a string. Your code is more speaking then. Since PHP 5.4 this is a one-liner:

$ext  = (new SplFileInfo($path))->getExtension();
like image 23
hakre Avatar answered Nov 14 '22 00:11

hakre