7

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.

4
  • What do you mean by "encode a Base64 string"? Convert a string to base64 representation? Can you include javascript, php that you have tried at Question? Commented Feb 10, 2017 at 18:04
  • No, I mean, how can I make it "URL-safe", because it contains some / and + and = Commented Feb 10, 2017 at 18:06
  • @JohnBrunner See my answer, let me know if you need a more fleshed out example. Commented Feb 10, 2017 at 18:17
  • Why can you not use POST request? How is base64 string generated? Commented Feb 10, 2017 at 18:34

2 Answers 2

23

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

Sign up to request clarification or add additional context in comments.

5 Comments

nodejs does not appear at tags at Question?
Thank you for your answer, but I think I asked the question wrong. I already got a Base64 string, and I want to send it via GET to my server. Problem is, that the Base64 string contains a lot of / and +, which is not safe for GET. How can I send it safely via GET?
@JohnBrunner To send it safely via a GET request you have to urlencode it client side. See my updated answer (javascript) for how todo that. Cheers.
@JohnBrunner Was my answer what you were looking for?
To be clear it should be reversed in php: echo base64_decode(urldecode($str));
0

In Javascript

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

In php

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.