忽然之间的博客

Thoughts, stories and ideas.

Base64编码URL参数注意

Base64编码后的字符,常用来作为URL参数传递。但有些情况下,编码后可能出现字符+/,在URL中就不能直接作为参数。

一般需要做URL Safe编码,就是把字符+/分别变成-_: `

截取Yii框架实现代码。


/** * Encodes string into "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648) * * > Note: Base 64 padding `=` may be at the end of the returned string. * > `=` is not transparent to URL encoding. * * @see https://tools.ietf.org/html/rfc4648#page-7 * @param string $input the string to encode. * @return string encoded string. * @since 2.0.12 */ public static function base64UrlEncode($input) { return strtr(base64_encode($input), '+/', '-_'); } /** * Decodes "Base 64 Encoding with URL and Filename Safe Alphabet" (RFC 4648) * * @see https://tools.ietf.org/html/rfc4648#page-7 * @param string $input encoded string. * @return string decoded string. * @since 2.0.12 */ public static function base64UrlDecode($input) { return base64_decode(strtr($input, '-_', '+/')); }