Home > Software engineering >  How to check the file type with Laravel Facades?
How to check the file type with Laravel Facades?

Time:03-25

Is there a convenient way to check the file type of a file with the File facade? I can check the file extension like so:

$ext = File::extension('623d91b094472.png');

I know I can derive the file type from the file extension but it would require some conditional string manipulation, so was wondering if there is a more convenient way to just get it from a facade like File::type(...) or such.

I need the file type because I'm encoding files in Vue.js and decoding them in Laravel, which requires the replacement of the file type and file extension in the base64 string:

$file64 = str_replace('data:image/png;base64,', '', $request->file);

I've tried this:

$type = File::type('623d91b094472.png');

but it throws:

local.ERROR: filetype(): Lstat failed for 623d91b094472.png {"userId":16,"exception":"[object] (ErrorException(code: 0): filetype(): Lstat failed for 623d91b094472.png at /Users/artur/PhpstormProjects/safa-ameedee.com/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:433)
[stacktrace]

CodePudding user response:

What do you mean by file type?

You can extract the extensions from base64 with the following code, I don't think Laravel has any builtin methods for this.

<?php

$base64string = "data:image/png;base64,...";
$fileExt = explode('/', explode(':', substr($base64string, 0, strpos($base64string, ';')))[1])[1];

echo $fileExt; // returns "png"

Also you can use something like Image package to create and manipulate the image from base64 string.

CodePudding user response:

You can use getClientMimeType() method on uploaded files. $file->getClientMimeType();

  • Related