Is there an easy way to check if a base64 image url is valid? I'm getting the base64 url from server via ajax/xhr and want to avoid xss on my site.
There are numerous ways to check if a string is valid base64. We are going to use one of the easiest solutions which involve the usage of the match () method and ternary (?) operator. The match () method matches a string against a regular expression. If the match is found, it returns an array of matches, otherwise returns null.
In PHP, you can create image from base64 and then verify the size and mime type to confirm if the base_64 data was valid or not. $data will contain array with all the data related to image.. size & mimetype etc.. so how I can validate the image just under < 2MB ?
Base64 Validator. The Base64 validator checks whether the submitted text is a valid Base64 encoded string. It allows you to validate online a variety of Base64 standards. Therefore, try to specify another standard, if one of them failed.
Base64 is an encoding scheme that represents binary data in ASCII string format. This makes it easy to send data over the internet via email or HTML form. Not only this but you can also convert an entire image to a base64 encoded string and use it as a source for an img tag. There are numerous ways to check if a string is valid base64.
I wrote an async function using @wolfshirts answer. It worked for me.
@wolfshirts function will not work because the return line was placed in the wrong scope.
async function isBase64UrlImage(base64String: string) {
let image = new Image()
image.src = base64String
return await (new Promise((resolve)=>{
image.onload = function () {
if (image.height === 0 || image.width === 0) {
resolve(false);
return;
}
resolve(true)
}
image.onerror = () =>{
resolve(false)
}
}))
}
I'm not sure if you're trying to validate the image itself, or the URL. Validating the image can be tricky. I would first run a check against known base64 MIME types.
'/' means jpeg.
'i' means png.
'R' means gif.
'U' means webp.
let data = //suspectedBase64Image
function isImage(data){
let knownTypes = {
'/': 'data:image/jpg;base64,',
'i': 'data:image/png;base64,',
/*ETC*/
}
let image = new Image()
if(!knownTypes[data[0]]){
console.log("encoded image didn't match known types");
return false;
}else{
image.src = knownTypes[0]+data
image.onload = function(){
//This should load the image so that you can actually check
//height and width.
if(image.height === 0 || image.width === 0){
console.log('encoded image missing width or height');
return false;
}
}
return true;
}
This is some basic sanity checking you could use.
You could go deeper and convert magic numbers to base64 then check for them within the base64 data. This code makes the assumption that you're missing the data type at the start. Some base64 will have the data type shown in the dictionary at the start of the base64.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With