Find the extension of files without extension in Laravel

Amit Merchant · June 11, 2020 ·

It’s helpful sometimes when you have a file and it doesn’t have extension attached to it but you want to know the extension of the file regardless.

For instance, If I’ve png file named foo.png and if I want to get the extension of this file, Laravel has got extension method on File facade which can be used to get the extension when the file has got the extension attached like so.

File::extension(public_path('foo.png'))
// "png"

But, as I mentioned earlier, if the file has no extension, say the png file with name foo only, how would you get the extension for the same?

Well, according to this PR, there will be a guessedExtension method on the File facade, which will try to “guess” the extension of the file like so.

File::guessedExtension(public_path('foo'))
// "png"

File::guessedExtension(public_path('desktop'))
// "jpg"

Behind scenes, the method tries to guess the extension by the mime-type of the file using Symfony’s MimeType extension.

Quite a little thing but it’s worth knowing about!

Hi there! I'm Amit. I write articles about all things web development. If you like what I write, buy me a coffee. I'd highly appreciate that. Cheers!

Newsletter

Follow me on Twitter @amit_merchant