Search code examples
javascriptphpbase64decodeencode

Encoding with JS base64 and deciding with php base64_decode


I'm sending users to a new link which has a value that is encoded with Javascript's btoa, however, on the PHP side, when I decode it and echo the value out, the value that is echoed out is "undefined"

    $("#btn-print-bonus").click(function(){
        var id = btoa(id);
        window.open('/pdf/?type=bonus&id='+id+'&name='+fullname+'');
    });

php file

$id = base64_decode($_GET["id"]);
echo $id;

Solution

  • here's the problem - var id = btoa(id);

    var id will "mask" any var named id outside of that click callback, so in effect you are doing

    var id = undefined;
    id = btoa(id);
    

    Which results in id=dW5kZWZpbmVk passed to php - check in the developer tools network tab and see if I'm right

    dW5kZWZpbmVk is the string "undefined" base64 encoded - btoa coerces the given argument to a string