Why is base64_encode() adding a slash "/" in the result?
There is nothing special in that.
The base 64 "alphabet" or "digits" are A-Z,a-z,0-9 plus two extra characters + (plus) and / (slash).
You can later encode / with %2f if you want.
In addition to all of the answers above, pointing out that /
is part of the expected base64
alphabet, it should be noted that the particular reason you saw a /
in your encoded string, is because when base64
encoding ASCII
text, the only way to generate a /
is to have a question mark in a position divisible by three.
Sorry, you thought wrong. A-Za-z0-9 only gets you 62 characters. Base64 uses two additional characters, in PHP's case /
and +
.
No. The Base64 alphabet includes A-Z, a-z, 0-9 and +
and /
.
You can replace them if you don't care about portability towards other applications.
See: http://en.wikipedia.org/wiki/Base64#Variants_summary_table
You can use something like these to use your own symbols instead (replace -
and _
by anything you want, as long as it is not in the base64 base alphabet, of course!).
The following example converts the normal base64 to base64url as specified in RFC 4648:
function base64url_encode($s) {
return str_replace(array('+', '/'), array('-', '_'), base64_encode($s));
}
function base64url_decode($s) {
return base64_decode(str_replace(array('-', '_'), array('+', '/'), $s));
}