Image To Base64 Converter helps you to convert an image to Base64 code, you could use the code in CSS Background, Image and so on. You may need Base64 to Image converter Select files here or drag and drop image files into the box. How to check if a string is base64 valid in PHP. Ask Question 47. I have a string and want to test using PHP if it's a valid base64 encoded or not. Php validation base64. Share| improve this question. Edited Oct 7 '13 at 11:22. I code a solution to validate images checking the sintaxy. Base64 Decode tool is to decode your String using Base64 Decoder Online: This utiltiy will Decode string to Base64.
Base64 is a generic term for a number of similar encoding schemes that encode binary data by treating it numerically and translating it into a base 64 representation. The Base64 term originates from a specific MIME content transfer encoding.
Is there a way in C# to see if a string is Base 64 encoded other than just trying to convert it and see if there is an error? I have code code like this:
I want to avoid the 'Invalid character in a Base-64 string' exception that happens if the value is not valid base 64 string. I want to just check and return false instead of handling an exception because I expect that sometimes this value is not going to be a base 64 string. Is there some way to check before using the Convert.FromBase64String function?
Thanks!
Update:
Thanks for all of your answers. Here is an extension method you can all use so far it seems to make sure your string will pass Convert.FromBase64String without an exception. .NET seems to ignore all trailing and ending spaces when converting to base 64 so '1234' is valid and so is ' 1234 '
For those wondering about performance of testing vs catching and exception, in most cases for this base 64 thing it is faster to check than to catch the exception until you reach a certain length. The smaller the length faster it is
In my very unscientific testing:For 10000 iterations for character length 100,000 - 110000 it was 2.7 times faster to test first.
For 1000 iterations for characters length 1 - 16 characters for total of 16,000 tests it was 10.9 times faster.
I am sure there is a point where it becomes better to test with the exception based method. I just don't know at what point that is.
abatishchevIt's pretty easy to recognize a Base64 string, as it will only be composed of characters 'A'..'Z', 'a'..'z', '0'..'9', '+', '/'
and it is often padded at the end with up to two '=', to make the length a multiple of 4. But instead of comparing these, you'd be better off ignoring the exception, if it occurs.
I know you said you didn't want to catch an exception. But, because catching an exception is more reliable, I will go ahead and post this answer.
Update: I've updated the condition thanks to oybek to further improve reliability.
Tomas KubesI believe the regex should be:
Only matching one or two trailing '=' signs, not three.
s
should be the string that will be checked. Regex
is part of the System.Text.RegularExpressions
namespace.
Why not just catch the exception, and return False?
This avoids additional overhead in the common case.
Tyler EavesTyler EavesJust for the sake of completeness I want to provide some implementation.Generally speaking Regex is an expensive approach, especially if the string is large (which happens when transferring large files). The following approach tries the fastest ways of detection first.
EDIT
As suggested by Sam, you can also change the source code slightly. He provides a better performing approach for the last step of tests. The routine
can be used to replace if (!Base64Chars.Contains(value[i]))
line with if (IsInvalid(value[i]))
The complete source code with enhancements from Sam will look like this (removed comments for clarity)
The answer must depend on the usage of the string. There are many strings that may be 'valid base64' according to the syntax suggested by several posters, but that may 'correctly' decode, without exception, to junk. Example: the 8char string Portland
is valid Base64. What is the point of stating that this is valid Base64? I guess that at some point you'd want to know that this string should or should not be Base64 decoded.
In my case, I have Oracle connection strings that may be in plain text like:
or in base64 like
I just have to check for the presence of a semicolon, because that proves that it is NOT base64, which is of course faster than any above method.
RolandRolandKnibb High football rules!
This should be relatively fast and accurate but I admit I didn't put it through a thorough test, just a few.
It avoids expensive exceptions, regex, and also avoids looping through a character set, instead using ascii ranges for validation.
I will use like this so that I don't need to call the convert method again
Imho this is not really possible. All posted solutions fails for strings like 'test' and so on. If they can be divided through 4, are not null or empty, and if they are a valid base64 character, they will pass all tests. That can be many strings ...
So there is no real solution other than knowing that this is a base 64 encoded string. What I've come up with is this:
I expect that the decoded string begins with a certain structure, so I check for that.
testingtestingSure. Just make sure each character is within a-z
, A-Z
, 0-9
, /
, or +
, and the string ends with . (At least, that's the most common Base64 implementation. You might find some implementations that use characters different from /
or +
for the last two characters.)
Yes, since Base64 encodes binary data into ASCII strings using a limited set of characters, you can simply check it with this regular expression:
/^[A-Za-z0-9=+/sn]+$/s
which will assure the string only contains A-Z, a-z, 0-9, '+', '/', '=', and whitespace.
I would suggest creating a regex to do the job.You'll have to check for something like this: [a-zA-Z0-9+/=]You'll also have to check the length of the string. I'm not sure on this one, but i'm pretty sure if something gets trimmed (other than the padding '=') it would blow up.
Or better yet check out this stackoverflow question
I like the Idea of a Regular Expression check. Regular Expressions can be fast, and save the coding overhead at times. the Original inquiry, had an update that did just this. I find though, that I can never assume the strings would not be null. I would expand the Extension function to check the source string for null, or whitespace only characters.
I have just had a very similar requirement where I am letting the user do some image manipulation in a <canvas>
element and then sending the resulting image retrieved with .toDataURL()
to the backend. I wanted to do some server validation before saving the image and have implemented a ValidationAttribute
using some of the code from other answers:
As you can see I am expecting an image/png type string, which is the default returned by <canvas>
when using .toDataURL()
.
Do decode, re encode and compare the result to original string