Validating base64 encoded images
One way of doing this would be to actually create an image file from the base64 data, then verify the image itself with PHP. There might be a simpler way of doing this, but this way should certainly work.
Keep in mind that this only really works for PNGs, you'll need to add some logic if you're planning on allowing more file types (GIF, JPG).
<?
$base64 = "[insert base64 code here]";
if (check_base64_image($base64)) {
print 'Image!';
} else {
print 'Not an image!';
}
function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
if (!$img) {
return false;
}
imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');
unlink('tmp.png');
if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;
}
return false;
}
?>
Python - Is Base64 data a valid image?
The PNG format has a fixed header that consists of the 8 bytes 89 50 4e 47 0d 0a 1a 0a
which, when converted to base64, look like this:
iVBORw0KGgo=
As you can see, it ends with a padding character "=", which will not be there in a real base64 representation of an image, and instead of "o" there could be a different character depending on the bytes after the header.
So you can easily recognize a base64 encoded PNG by comparing the first characters of the base64 string with
iVBORw0KGg
This principle works for all file formats that have a fixed header.
Validating a base64 encoded image .NET core
When you don't have System.Drawing I would look at the actual bytes instead to see if they match the JPEG or PNG file standard.
For a PNG file the first eight bytes always contains the following decimal values: 137 80 78 71 13 10 26 10
(Source)
A JPEG file is more complex but it can be done as well. The first two bytes, at least, seems to always be 0xFF 0xD8
(Source). Read a bit more about the file structure to get better comparison values.
Based on this you can do a simple comparison on the bytes in your imageBytes
array.
How to validate base 64 string with Laravel 4.2
Use:
if (!base64_decode($value))
base64_decode will return false on non base64 string.
Related Topics
How to Fix Undefined Offset: 0 in Laravel Blade
How to Get Next Id of Autogenerated Field in Laravel for Specific Table
How to Restrict User from Downloading or Saving Pdf File
Laravel 5.5 Error 500 in Cpanel Shared Hosting
How to Install and Use PHP on Macos Via Brew
How to Convert Jquery Ajax Success Data to a PHP Variable
Laravel Storage Link Won't Work on Production
How to Convert Ereg Expressions to Preg in PHP
Reference - Frequently Asked Questions About Pdo
How to Prevent a User from Directly Accessing My HTML Page by Writing Url
How to Update Field to Add Value to Existing Value
Telegram Bot Api: How to Send a Photo Using PHP
How to Get the Domain Name Without Www, Subdomain, and Com/Net/Org/Etc
Redirect That Same Page from Where Id Is Coming
How to Sends Two Values in Select Dropdown Using PHP
Preventing Direct Access to a PHP Page, Only Access If Redirected