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 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据