Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Find the extension of files without extension in Laravel

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.

use Illuminate\Support\Facades\File;

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.

Update: The guessedExtension method has now renamed to guessExtension from Laravel 8.x.

use Illuminate\Support\Facades\File;

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

File::guessExtension(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!

Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?