Possible Duplicate:
How to extract a file extension in PHP?
Get the file extension (basename?)
trying tot learn from other people´s code , I see a lot of methods to strip a filename from it´s extension, but most of the methods seems too localized as they assume a certain condition. for example :
This will assume only 3-character extension (like .txt, .jpg, .pdf)
substr($fileName, 0, -4);
or
substr($fileName, 0, strrpos($fileName, '.'));
But this can cause problems on file names like .jpeg, .tiff .html . or only 2 like .jsOr .pl
(browsing this list shows some file names can have only 1 character, and some as many as 10 (!) )
some other methods i have seen rely on the point (.)
for example :
return key(explode(“.”, $filename));
Can cause problems with filenames like 20121029.my.file.name.txt.jpg
same here :
return preg_replace('/\.[^.]*$/', '', $filename);
some people use the pathinfo($file) and / or basename() (is it ALWAYS safe ?? )
basename($filename);
and many many other methods ..
so my question has several parts :
-
what is the best way to “strip” a file extension ? (with the point)
-
what is the best way to “get” the file extension (without the point) and / or check it
-
will php own functions (basename) will recognize ALL extensions regardless of how exotic they might be or how the filename is constructed ?
-
what if any influence does the OS has on the matter ? (win, linux, unix…)
- all those small sub-questions , which i would like to have an answer to can be summed-up in an overall single question :
Is there a bullet-proof , overall, always-work, fail-proof , best-practice , über_function that will work under all and any condition ??
EDIT I – another file extension list
Quoting from the duplicate question’s top answer:
this is the best available way to go. It’s provided by the operating system, and the best you can do. I know of no cases where it doesn’t work.
One exception would be a file extension that contains a
.. But no sane person would introduce a file extension like that, because it would break everywhere plus it would break the implicit convention.Nope, it’s much simpler – and maybe that is the root of your worries. The extension of
20121021.my.file.name.txt.tar.gzis.gz. It is a gzipped.gzfile for all intents and purposes. Only when you unzip it, it becomes a.tarfile. Until then, the.tarin the file name is meaningless and serves only as information for thegunziptool. There is no file extension named.tar.gz.That said, detecting the file extension will not help you determine whether a file is actually of the type it claims. But I’m sure you know that, just putting this here for future readers.