Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Umlauts issue when Base64 encoding in JS and decoding in PHP

I searched a lot but still haven't found the reason for my problem:

When calling my php webservice I am encoding the login credentials ("PeterPan:Ützel([])ÄÄÖÖ'") and passing them using UTF-8:

$.ajaxSetup({
        beforeSend: function(request) {
            request.setRequestHeader("Authentication", auth);
        },
        type: "POST",
        contentType: "charset=utf-8"
    });
var tok = sUsername + ':' + sPassword;
    var hash = this.Base64.encode(tok);
    var auth = hash;
$.ajax({
        url: "php/login.php"
    });

In PHP, I am decoding the string by using:

$headers = array();
foreach($_SERVER as $key => $value) {
    if (substr($key, 0, 5) <> 'HTTP_') {
        continue;
    }
    $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))));
    $headers[$header] = $value;
}

$response['Encoded'] = base64_decode($headers['Authentication']);
$encoded = json_encode($response);
header("Content-Type: text/html; charset=utf-8");
echo $encoded;

When the response arrives, the encoded string looks like this: "PeterPan:\u00dctzel([])\u00c4\u00c4\u00d6\u00d6'"

The umlauts are incorrectly encoded...

What am I doing wrong?

like image 906
AntonSack Avatar asked Mar 27 '26 20:03

AntonSack


1 Answers

You could to do the following

The javascript :

// returns PeterPan%3A%C3%9Ctzel(%5B%5D)%C3%84%C3%84%C3%96%C3%96
var value = encodeURIComponent(sUsername + ':' + sPassword);

The PHP :

header('Content-Type: text/html; charset=utf-8'); // might need this

// returns PeterPan:Ützel([])ÄÄÖÖ
echo rawurldecode("PeterPan%3A%C3%9Ctzel(%5B%5D)%C3%84%C3%84%C3%96%C3%96");
like image 112
Sparkup Avatar answered Mar 30 '26 09:03

Sparkup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!