donglu1971
2018-03-16 12:10
浏览 327
已采纳

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

图片转代码服务由CSDN问答提供 功能建议

我使用的数组编码为json,而不是BASE64,保存在Cookie中, 稍后检索。 实际的字符串是:

  {“insert”:0,“delete”:0} 
   
  
 

在PHP中我有:

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

Cookie存储为:

  eyJpbnNlcnQiOjEsImRlbGV0ZSI6MH0%3D 
   
 
 

最后的“%3D”应为“=”,以便填充base64的其余部分,因此返回奇怪的字符, 但我做不到。 有什么想法? 提前谢谢

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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

    打赏 评论

相关推荐 更多相似问题