Why is base64_encode() adding a slash “/” in the r

2019-01-22 01:58发布

I am encoding the URL suffix of my application:

$url = 'subjects?_d=1';
echo base64_encode($url);

// Outputs
c3ViamVjdHM/X2Q9MQ==

Notice the slash before 'X2'.

Why is this happening? I thought base64 only outputted A-Z, 0-9 and '=' as padding? I have tried using an online base64 encoder to check, and it seems base64 always does this. I can't tell if it's the underscore "_" or the question mark "?" or the "=" perhaps?

7条回答
劫难
2楼-- · 2019-01-22 02:15

Not directly related, and enough people above have answered and explained solutions quite well.

However, going a bit outside of the scope of things. If you want readable base text, try looking into Base58. It's worth considering if you want only alphanumeric characters.

查看更多
聊天终结者
3楼-- · 2019-01-22 02:16

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.

查看更多
放荡不羁爱自由
4楼-- · 2019-01-22 02:17

Sorry, you thought wrong. A-Za-z0-9 only gets you 62 characters. Base64 uses two additional characters, in PHP's case / and +.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-22 02:25

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.

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-22 02:26

A-Z is 26 characters. 0-9 is 10 characters. = is one character. That gives a total of 37 characters, which is some way short of 64.

/ is one of the 64 characters. You can see a complete list on the wikipedia page.

查看更多
手持菜刀,她持情操
7楼-- · 2019-01-22 02:35

For base64 the valid charset is: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

the = is used as filler for the last bytes

M.

查看更多
登录 后发表回答