Kayl Max Kayl Max - 12 days ago 10
PHP Question

Decode back Javascript base64 unicode with PHP

I have this encode function in Javascript:

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


How to decode it under PHP ?

I tried:

htmlspecialchars_decode(base64_decode($str));


But i got a depreciated characters like:

�]��\��H���


Can you suggest a solution please ?

Example of encoded html code:

<div class="pattern">
<div class="gbody"></div>
<div class="eyes">
<div class="eye left"></div>
<div class="eye right"></div>
</div>
<div class="mouth"></div>
<div class="wave"></div>
<div class="gshadow"></div>
</div>


The javascript return:

CiAgPGRpdiBjbGFzcz0iZ2JvZHkiPjwvZGl2PgogIDxkaXYgY2xhc3M9ImV5ZXMiPgogICAgPGRpdiBjbGFzcz0iZXllIGxlZnQiPjwvZGl2PgogICAgPGRpdiBjbGFzcz0iZXllIHJpZ2h0Ij48L2Rpdj4KICA8L2Rpdj4KICA8ZGl2IGNsYXNzPSJtb3V0aCI PC9kaXY CiAgPGRpdiBjbGFzcz0id2F2ZSI PC9kaXY CiAgPGRpdiBjbGFzcz0iZ3NoYWRvdyI PC9kaXY CjwvZGl2Pg==


Here the decode function in Javascript:

function b64DecodeUnicode(str) {
return decodeURIComponent(Array.prototype.map.call(atob(str), function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}


EDIT:

str
with chinese characters:

CiAgPGRpdiBjbGFzcz0iZ2JvZHkiPjwvZGl2PgogIDxkaXYgY2xhc3M9ImV5ZXMiPgogICAg5Lq65rCR6ZOB6YGT572R5piv55Sx5Lit5Y2O5Lq65rCR5YWx5ZKM5Zu96ZOB6YGT6YOo5pS/5rK76YOo5a6j5Lyg6YOo5Li7566h44CB5Lq65rCR6ZOB6YGT5oql56S+5Li75Yqe44CB5oOf5LiA6I635b6X5Zu95Yqh6Zmi5paw6Ze75Yqe5om55YeG55qE5YW35pyJ5paw6Ze75Y+R5biD6LWE6LSo55qE6ZOB6Lev6KGM5Lia572R56uZ77yM5Lq65rCR6ZOB6YGT572R56uL6Laz6ZOB6LevCiAgICA8ZGl2IGNsYXNzPSJleWUgbGVmdCI+PC9kaXY+CiAgICA8ZGl2IGNsYXNzPSJleWUgcmlnaHQiPjwvZGl2PgogIDwvZGl2PgogIDxkaXYgY2xhc3M9Im1vdXRoIj48L2Rpdj4KICA8ZGl2IGNsYXNzPSJ3YXZlIj48L2Rpdj4KICA8ZGl2IGNsYXNzPSJnc2hhZG93Ij48L2Rpdj4KPC9kaXY


NB: The Javascript encode function is required in my project.

Answer

base64_decode is enough. Your problem is (probably) how you send your js-base64encoded string to php.

b64EncodeUnicode can't return this:

CiAgPGRpdiBjbGFzcz0iZ2JvZHkiPjwvZGl2PgogIDxkaXYgY2xhc3M9ImV5ZXMiPgogICAgPGRpdiBjbGFzcz0iZXllIGxlZnQiPjwvZGl2PgogICAgPGRpdiBjbGFzcz0iZXllIHJpZ2h0Ij48L2Rpdj4KICA8L2Rpdj4KICA8ZGl2IGNsYXNzPSJtb3V0aCI PC9kaXY CiAgPGRpdiBjbGFzcz0id2F2ZSI PC9kaXY CiAgPGRpdiBjbGFzcz0iZ3NoYWRvdyI PC9kaXY CjwvZGl2Pg==

Do you see the spaces? b64EncodeUnicode probably returned this instead:

CiAgPGRpdiBjbGFzcz0iZ2JvZHkiPjwvZGl2PgogIDxkaXYgY2xhc3M9ImV5ZXMiPgogICAgPGRpdiBjbGFzcz0iZXllIGxlZnQiPjwvZGl2PgogICAgPGRpdiBjbGFzcz0iZXllIHJpZ2h0Ij48L2Rpdj4KICA8L2Rpdj4KICA8ZGl2IGNsYXNzPSJtb3V0aCI+PC9kaXY+CiAgPGRpdiBjbGFzcz0id2F2ZSI+PC9kaXY+CiAgPGRpdiBjbGFzcz0iZ3NoYWRvdyI+PC9kaXY+CjwvZGl2Pg==

What you need to do to solve your problem? For instance, if you pass it inside the querystring of the php page, you should url-encode it. You can use encodeURIComponent to do it.

Comments