Can a base64 encoded string contain whitespace? Can a base64 encoded string contain whitespace? php php

Can a base64 encoded string contain whitespace?


No it can't. See Base64 for the allowed character repository used by base64, which are the characters A-Z, a-z, 0-9, + and / (the last two may differ depending on the implementation) as well as the padding character = (but that's also implementation dependent as some implementations don't use padding at all).


It shouldn't, but it might do.

A valid base64 string should not contain whitespace since the encoding alphabet should only consist of A-Z a-z 0-9 + /

However, if the encoded data happens to contain a '+' character, and the data is passed in a URL, it can be unintentionally converted into a space. So you may come across a supposed base64 string that appears to have spaces in it under these circumstances.

If this is the case, simply replace spaces with pluses before decoding.

PS. I'm thinking about the whole "MySQL will trim trailing whitespace when storing strings in VARCHAR fields" here

As an aside, the trailing whitespaces of a varchar won't be casually stripped as of MySQL 5.0.3


Yes. Base64-encoded string can contain white-spaces but the characters are not significant. So it's ok if database trims spaces.

As a matter of fact, the original MIME specification recommends to break Base64 strings into lines of 72 characters. base64Binary of XML may also include newlines, tabs, spaces.

In PHP, base64_decode() strips all whiltespace characters so you don't have to worry about it.