donglu1971 2018-03-16 12: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 12: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

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

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了