为什么base64_encode()添加斜杠“/”在结果中? [英] Why is base64_encode() adding a slash "/" in the result?

查看:5081
本文介绍了为什么base64_encode()添加斜杠“/”在结果中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

//输出
c3ViamVjdHM / X2Q9MQ ==

通知X2之前的斜杠。



为什么会发生这种情况?我以为base64只输出A-Z,0-9和'='作为填充?我已经尝试使用在线base64编码器来检查,似乎base64总是这样做。我不知道它是下划线_还是问号?或者=?

解决方案

Base64字母表包括AZ,az,0-9和 + /



如果您不关心其他应用程序的可移植性,可以替换它们。



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



您可以使用像这样的东西来使用你自己的符号来代替( - _ 只要它不在base64基本字母表中,当然!)。



以下示例将正常的base64转换为base64url 如RFC 4648 所述:

  function base64url_encode($ s){
return str_replace(array('+','/'),array(' - ','_'),base64_encode($ s));
}

函数base64url_decode($ s){
返回base64_decode(str_replace(array(' - ','_'),array('+','/' ,$ s));
}


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?

解决方案

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

这篇关于为什么base64_encode()添加斜杠“/”在结果中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆