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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)