I am trying to add a validation in my Symfony controller where I need to validate file types of base64 image. So basically I am sending base64 images to the backend and there I am checking whether the file is jpeg or png. If the file is anything other than those then the validation should fail.
So my code seems to be working fine for JPEG and PNG where it passes the validation and fails for WebP. But when I try with a base64 SVG file, it passes as well (which should not pass). If I debug it, I can see the mime type of the file as image/png. So apparently it is being identified as a PNG file.
What could be the reason for this? And how can I fix it?
Here’s the code:
public function isAllowed(array $file): bool
{
$fileType = $file['filetype'];
$base64Image = $file['base64'];
$binaryData = base64_decode($base64Image);
$directoryPath = '/var/www/tmp';
if (!is_dir($directoryPath)) {
mkdir($directoryPath, 0777, true);
}
$tempFileName = tempnam($directoryPath, 'uploaded_file');
file_put_contents($tempFileName, $binaryData);
$file = new File($tempFileName);
$validatorBuilder = Validation::createValidatorBuilder();
$validator = $validatorBuilder->getValidator();
$constraints = [
new SymfonyComponentValidatorConstraintsFile([
'mimeTypes' => self::ALLOWED_IMAGE_FILE_TYPES
]),
];
$errors = $validator->validate($file, $constraints);
unlink($tempFileName);
return count($errors) > 0 ? false : true;
}
Please note:
- base64 string is without the first part. That is, if file has base64 string as
data:image/png;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjthen in the function it is onlyPHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMj. It is working fine without the first part. - Using Symfony 4.
- When a temp file is created, it doesn’t have any extension.