PHP Function To Get A File Extension From A String
Getting the file extension from a PHP string can be very important in validating a file or file upload. I've written a simple PHP function to retrieve a file extension from a string.
The Code
function get_file_extension($file_name)
{
return substr(strrchr($file_name,'.'),1);
}
Discussion
Be Heard!
Share your thoughts with fellow developers of all skill levels! I want to hear from you!
This looks really useful, thanks.
Why reinvent the wheel? We have good ol’ pathinfo() :
http://hu2.php.net/manual/en/function.pathinfo.php
Array
(
[dirname] => .
[basename] => some.file.extension
[extension] => extension
[filename] => some.file
)
I came up with this snippet to get the file extension as well, using array functions:
… and it got cut out. Here’s the function, without tags:
function get_file_extension($file_name) {
return end(explode(‘.’,$file_name));
}
As mentioned by ochronus the following code does the exact same thing:
$file = ‘/tmp/test.php’;
echo pathinfo($file, PATHINFO_EXTENSION);
or we can do it via end(explode(‘.’, “filename.ext)); easily
File extension from path:
function f_extension($fn){
$str=explode(‘/’,$fn);
$len=count($str);
$str2=explode(‘.’,$str[($len-1)]);
$len2=count($str2);
$ext=$str2[($len2-1)];
return $ext;
}
$extesnion=f_extension(“files/file.jpg”); // returns jpg
Try & enjoy!
What happens when you try to get the extension of “/etc/init.d/README” with the explode method?
Just use the pathinfo().
@Jorge: Either way works, and it just ends up being a matter of preference. You have to consider how this function will usually be used on a web application; it will be grabbing the extension and making sure it’s an allowed extension for upload. Thus, the explode method would return something that doesn’t match a valid extension (like your README example), and the file upload would get declined.
If you’re building a file explorer on the web, sure, use pathinfo(); that’s common sense. If you’re building a web app that takes uploads, then I can’t imagine the explode method would not be faster than pathinfo.
Thanks for sharing !
@crivion: please explain it with example
end(explode(‘.’, “filename.ext));,
explain how does it work