Last active
July 13, 2018 15:52
-
-
Save einnar82/aecceb50e757bc9447f539a5b0feb0ec to your computer and use it in GitHub Desktop.
Base 64 Image Validator in Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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() | |
{ | |
// | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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