https://tools.ietf.org/html/rfc3548
https://tools.ietf.org/html/rfc4648%EF%BC%8C%E5%BC%95%E8%87%AA%E7%BB%B4%E5%9F%BA%E7%99%BE%E7%A7%91:l
“This RFC obsoletes RFC 3548 and focuses on Base64/32/16.”
<?php // 测试 $encode = mbase64_encode("134dewdqew你好啊"); echo 'encode:' . $encode . PHP_EOL; $decode = mbase64_decode($encode); echo 'decode:' . $decode; //base64变形,为解决外部问题 // 编码:base64,已经测试,测试内容为中文字符串和英文字符串; function mbase64_encode($msg) { $content = '';//base64编码后得到的字符串,不包含结尾的 “=” $end = '';//结尾的 “=” 部分 $base64_chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']; $msglength = strlen($msg);//要编码的文本的总字节数 $b = $msglength % 3;//不是的 $end = $b == 0 ? '' : str_repeat('=', 3 - $b);//确定base64中‘=’的个数 $msg .= $b == 0 ? '' : str_repeat("\0", 3 - $b);//追加空字符,用于for循环处理 //开始处理报文内容,每次处理3Byte,因为3Byte处理起来方便; for ($index = 0; $index < strlen($msg); $index += 3) { //获取要处理的序列,此步骤得到的是$msg中的要进行编码的三个字符 $tmp_msg = (ord($msg[$index]) << 16) + (ord($msg[$index + 1]) << 8) + (ord($msg[$index + 2])); //生成编码后的四个字符 for($m = 3; $m > -1; $m--){ $char_index = ($tmp_msg >> ($m * 6)) & 63; $content .= $base64_chars[$char_index];//取到对应的字符 } } //截取字符串,用于删除由于追加空字符而产生的多余字符,之后拼接结尾的 “=” return substr($content, 0, strlen($content) - strlen($end)) . $end; } // 解码:已测试,测试内容为“中英文混合的base64编码” function mbase64_decode($msg){ $base64_chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/']; $msg = str_replace('=', 'A', $msg, $rep_count);//将“=”替换为“A”,并获取替换的次数,即“=”的个数 $content = '';//解码后的文本内容; for($index = 0; $index < strlen($msg); $index += 4) { //4个字符为一组处理,先组成24bit $tmp_content = ''; for($m = 0; $m < 4; $m++){ $tmp_content = ($tmp_content << 6) + array_search($msg[$index + $m], $base64_chars); } //将24bit,转化为三个字符 $tmp_sub_msg = ''; for($n = 0; $n < 3; $n++){ $tmp_sub_msg = chr(($tmp_content >> ($n * 8)) & 255) . $tmp_sub_msg; } $content .= $tmp_sub_msg; } //删除多余的字节,多余的字节为代替“=”的“A” return substr($content, 0, strlen($content) - $rep_count); }