您可以使用以下代码验证文件类型:
$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');
}
Run Code Online (Sandbox Code Playgroud)
在$mime_type你会得到类似application/pdf或的东西image/jpeg。
在$file_type你会得到一个文件类型 f.ex。图片。
在$extension你之下你会得到一个扩展。
有了finfo_buffer你可以使用一些预定义的常量,它可以给你更多的信息。
使用这些信息,您可以简单地验证它是图像还是 pdf 或您想要检查的任何其他内容。您可以在此页面中查看所有可用的 mimetypes 。
手动的