Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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
like image 502
Jozsef Naghi Avatar asked Mar 20 '15 12:03

Jozsef Naghi


2 Answers

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);
like image 100
Grokify Avatar answered Oct 19 '22 02:10

Grokify


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.

like image 36
deceze Avatar answered Oct 19 '22 01:10

deceze