Last active
October 1, 2023 15:47
-
-
Save nasrulhazim/f3ca4c231216a491b423e06e069473ae to your computer and use it in GitHub Desktop.
Laravel Base64 and Base64 Image Validator
This file contains 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\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; | |
}); | |
} | |
/** | |
* Register any application services. | |
* | |
* @return void | |
*/ | |
public function register() | |
{ | |
if ($this->app->environment() == 'local') { | |
$this->app->register(\MaddHatter\ViewGenerator\ServiceProvider::class); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Bad base64image check, skips what shouldn't be skipped