You can validate file type with code below:
$file = 'Your base64 file string';
$file_data = base64_decode($file);
$f = finfo_open();
$mime_type = finfo_buffer($f, $file_data, FILEINFO_MIME_TYPE);
$file_type = explode('/', $mime_type)[0];
$extension = explode('/', $mime_type)[1];
echo $mime_type; // will output mimetype, f.ex. image/jpeg
echo $file_type; // will output file type, f.ex. image
echo $extension; // will output extension, f.ex. jpeg
$acceptable_mimetypes = [
'application/pdf',
'image/jpeg',
];
// you can write any validator below, you can check a full mime type or just an extension or file type
if (!in_array($mime_type, $acceptable_mimetypes)) {
throw new \Exception('File mime type not acceptable');
}
// or example of checking just a type
if ($file_type !== 'image') {
throw new \Exception('File is not an image');
}
Under $mime_type
you will get something like application/pdf
or image/jpeg
.
Under $file_type
you will get a file type f.ex. image.
Under $extension
you will get an extension.
With finfo_buffer
you can use a few predefined constants, which may give you more informations.
With those informations you can simply validate if it's image or pdf or any other things you want to check. All the available mimetypes you can check in this page.
Manual
PHP: finfo_open
PHP: finfo_buffer
PHP: finfo_buffer - Predefined Constants
base64_decode
MIME types (IANA media types)