Jozsef Naghi
Jozsef Naghi

Reputation: 1095

Encoding special characters to Base64 in Javascript and decoding using base64_decode() in PHP

My problem is that the base64_decode() function does not work with special characters. Maybe the problem is that I am using an ajax event and I am parsing the data using base64.encode from javascript. js code:

description: $.base64.encode($("#Contact_description").val())

and this is the php code:

$model->description = base64_decode($model->description);

where $model->description is the $("#Contact_description").val() value

Example this is the description value : Traian Băsescu and this is how I look after using the decode from php : Traian A�sescu. What should I do ?

UPDATE: This the header information from firebug:

Content-Length  143
Content-Type    text/html; **charset=UTF-8**
Date    Fri, 20 Mar 2015 12:37:01 GMT

Upvotes: 11

Views: 15973

Answers (2)

deceze
deceze

Reputation: 522005

The problem is that Javascript strings are encoded in UTF-16, and browsers do not offer very many good tools to deal with encodings. A great resource specifically for dealing with Base64 encodings and Unicode can be found at MDN: https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

Their suggested solution for encoding strings without using the often cited solution involving the deprecated unescape function is:

function b64EncodeUnicode(str) {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
        return String.fromCharCode('0x' + p1);
    }));
}

For further solutions and details I highly recommend you read the entire page.

Upvotes: 12

Grokify
Grokify

Reputation: 16324

The following works for me:

JavaScript:

// Traian Băsescu encodes to VHJhaWFuIELEg3Nlc2N1
var base64 = btoa(unescape(encodeURIComponent( $("#Contact_description").val() )));

PHP:

$utf8 = base64_decode($base64);

Upvotes: 11

Related Questions