How to validate base64 image , size and mime type in lumen api?

· · 19450 views

Is there any best way to validate base64 encoded image, size and mime type in lumen api?

0
4 Answers

You can try this package to validators for base64 encoded files: https://github.com/crazybooot/base64-validation

1
gurpreet
gurpreet ·

This package will delete some file in the lumen. I tried but I m facing issues with this package.

You can extend the Validator class.

Laravel Doc

But anyway try this

Validator::extend('is_png',function($attribute, $value, $params, $validator) {
    $image = base64_decode($value);
    $f = finfo_open();
    $result = finfo_buffer($f, $image, FILEINFO_MIME_TYPE);
    return $result == 'image/png';
});

And then validate like this:

$rules = array(
   'image' => 'is_png'
);
0

Create your own Base64 and Base64 Image Validator using following snippet:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        Validator::extend('base64', function ($attribute, $value, $parameters, $validator) {
            if (preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $value)) {
                return true;
            } else {
                return false;
            }
        });

        Validator::extend('base64image', function ($attribute, $value, $parameters, $validator) {
            $explode = explode(',', $value);
            $allow = ['png', 'jpg', 'svg'];
            $format = str_replace(
                [
                    'data:image/',
                    ';',
                    'base64',
                ],
                [
                    '', '', '',
                ],
                $explode[0]
            );

            // check file format
            if (!in_array($format, $allow)) {
                return false;
            }

            // check base64 format
            if (!preg_match('%^[a-zA-Z0-9/+]*={0,2}$%', $explode[1])) {
                return false;
            }

            return true;
        });

    }
}
0

I found this article which I think is useful for you. In this aritcle, It has shown how to create validation rule for encoded image:

https://itnext.io/laravel-validation-rule-encoded-image-4a43b433fca7

0

Please login or create new account to participate in this conversation.