donglu1971 2018-03-16 04:10
浏览 504
已采纳

PHP base64_encode在字符串末尾添加奇怪的字符

I´m using an array, which I encode into json, than into BASE64, save it on a Cookie, to be later on retrieved. The actual string is:

{"insert":0,"delete":0}

In PHP I have:

$Sync = json_encode($update);
setcookie('Sync',strtr(base64_encode($Sync), '+/', '-_'), 0, "/");

The Cookie is being stored as:

eyJpbnNlcnQiOjEsImRlbGV0ZSI6MH0%3D

That final "%3D" should be "=" so to fill the rest of the base64, nad therefore return strange characters, but I can´t get it right. Any ideas? Thanks in advance

  • 写回答

1条回答 默认 最新

  • dongru2019 2018-03-16 04:28
    关注

    Within the docs on php.net (http://php.net/manual/en/function.base64-encode.php#103849) the top comment provides two functions that should help you (similar to your implementation as well :))

    For anyone interested in the 'base64url' variant encoding, you can use this pair of functions:

    <?php 
    function base64url_encode($data) { 
      return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
    } 
    
    function base64url_decode($data) { 
      return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT)); 
    } 
    ?>
    

    Within your implementation, it looks like you need to wrap strtr(base64_encode($Sync), '+/', '-_'), 0, "/") with rtrim, like so:

    rtrim(strtr(base64_encode($Sync), '+/', '-_'), 0, "/"), '=')
    

    Results: https://3v4l.org/5D1Mk

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部