0

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]
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132

3 Answers3

0

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"

$fileType = explode('/', explode(':', substr($base64string, 0, strpos($base64string, ';')))[1])[0];

echo $fileType; // returns "image"

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

Karlo
  • 152
  • 3
  • 9
  • By file type I mean the `image` in front of the `/png` in the `base64` string. For example Vuejs encodes `png` and `jpg` files as `image` and `pdf` files as `application`. I was hoping there is some consensus between both frameworks on how to encode stuff and it might be supported. – Artur Müller Romanov Mar 25 '22 at 11:06
  • I've update my code to show how to get image string. These strings are not reliable as per this answer here: https://stackoverflow.com/questions/57976898/how-to-get-mime-type-from-base-64-string – Karlo Mar 25 '22 at 13:07
0

You can use getClientMimeType() method on uploaded files.

<?php $file->getClientMimeType();
0

You can use the PHP's inbuilt function getimagesizefromstring to get image mime from image string/base64 as:

$imageData = getimagesizefromstring($data);

$mime = $imageData['mime']; // image/png
$ext = explode('/', $mime)[1]; // png

echo $ext; //png
OMi Shah
  • 5,768
  • 3
  • 25
  • 34