Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Validate base64 encoded images

I need to find a way to validate an image that is base64 encoded in PHP.

By validate i'm thinking of XSS and other security things like that.

The flow is:

User has some parameters where one og more in a base64 encode string of an image and post them to my site. When i receive the parameter fx called img1 with the base64 encoded image string as value.

I would then like to make sure that this base64 encoded string only consist of the image and doest not have any tags and any other things hackers will try to use.

Does anyone know any PHP functions or plugins that can help me?

like image 666
Anders Gerner Avatar asked Dec 27 '22 18:12

Anders Gerner


1 Answers

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)

like image 89
Karol Gasienica Avatar answered Jan 10 '23 16:01

Karol Gasienica