Skip to content

Instantly share code, notes, and snippets.

@einnar82
Last active July 13, 2018 15:52
Show Gist options
  • Save einnar82/aecceb50e757bc9447f539a5b0feb0ec to your computer and use it in GitHub Desktop.
Save einnar82/aecceb50e757bc9447f539a5b0feb0ec to your computer and use it in GitHub Desktop.
Base 64 Image Validator in Laravel
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class Base64ServiceProvider extends ServiceProvider
{
/**
* Bootstrap services.
*
* @return void
*/
public function boot()
{
Validator::extend('image64', 'App\Validators\Base64Validator@validateBase64');
}
/**
* Register services.
*
* @return void
*/
public function register()
{
//
}
}
<?php
namespace App\Validators;
class Base64Validator
{
/**
* Check if the file is in base64 image
*/
public function validateBase64($attribute, $value, $parameters, $validator)
{
$explode = $this->explodeString($value);
$allow = $this->allowedFormat();
$format = $this->dataFormat($explode);
// 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;
}
/**
* Check the data format
*/
public function dataFormat($explode)
{
return str_replace(
[
'data:image/',
';',
'base64',
],
[
'', '', '',
],
$explode[0]
);
}
/**
* The allowed format in base 64 image
*/
public function allowedFormat()
{
return ['gif', 'jpg', 'jpeg', 'png'];
}
/**
* Explode base 64 image
*/
public function explodeString($value)
{
return explode(',', $value);
}
}
'image64' => 'The :attribute must be a valid base-64 string.',
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment