为什么 base64_encode() 添加斜杠“/"?结果呢?

2022-01-21 00:00:00 encoding base64 php

我正在编码我的应用程序的 URL 后缀:

I am encoding the URL suffix of my application:

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

// Outputs
c3ViamVjdHM/X2Q9MQ==

注意 'X2' 之前的斜线.

Notice the slash before 'X2'.

为什么会这样?我以为 base64 只输出 A-Z、0-9 和 '=' 作为填充?

Why is this happening? I thought base64 only outputted A-Z, 0-9 and '=' as padding?

推荐答案

没有.Base64 字母表包括 A-Z、a-z、0-9 和 +/.

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.

参见:http://en.wikipedia.org/wiki/Base64#Variants_summary_table

您可以使用类似的东西来使用您自己的符号(将 -_ 替换为您想要的任何内容,只要它不在 base64 基本字母表中,当然!).

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!).

以下示例将普通 base64 转换为 base64url 按照 RFC 4648 的规定:

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));
}

相关文章