Encode Base64 in JavaScript, send with GET, decode in PHP

北城以北 提交于 2019-12-02 07:25:58

问题


I thought this will be an easy Google-search, but it seems that my technique is not as common as I thought.

How can I encode a Base64 string in JavaScript, in order to put it safely on the line with a GET parameter (my Base64 string contains a lot of /, + and =, and decode the exact same string in PHP, in order to store it in a database?

When I post the Base64 string without encoding, my PHP script does not accept it.

I found a solution for encoding and decoding the Base64 string in JavaScript, but not in the way it makes sense for me.


回答1:


So in javascript (updated with encoding URI):

var myStr = "I am the string to encode";
var token = encodeURIComponent(window.btoa(myStr));

btoa example

You should be then able to add that base64 encoded string to your get request.

Then in PHP, after you retrieve the request:

<?php
   $str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
   echo base64_decode(urldecode($str));
?>

base64_decode docs




回答2:


In Javascript

var password ="xyz"
window.btoa(password)

In php

$password = urldecode(base64_decode($_POST['password']));


来源:https://stackoverflow.com/questions/42165891/encode-base64-in-javascript-send-with-get-decode-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!