Get File Extension in PHP
- 1 minute read
This short snippet accepts a string, $fileName
, and returns a lowercase version of all the text after the string’s last period:
function getExtension($fileName) {
$arr = explode('.', $fileName);
if ($arr !== false) {
return strtolower($arr[count($arr) - 1]);
} else {
return false; // No period was found
}
}
Here is some example output:
-
getExtension('hello.JPG')
returns.jpg
. -
getExtension('example.config.js')
returns.js
. -
getExtension('hello')
returnsfalse
, because there is no period.
Conclusion
That’s all! You can pass in any sort of string, such as a file path, file name, or URL.
I wanted to keep this post short, because this is just a concise snippet that does one simple task and does it well.