I’m working on a small application that communicates through JavaScript to a PHP script, and usually the data contains text in UTF-8 format to make everything as compatible as possible.
The text in UTF-8 format doesn’t go too well into an AJAX call GET URL. So it has to be further encoded with an encoding that can be used as a parameter. BASE64 is one such.
There’s a handy JavaScript BASE64 encoder available at webtoolkit.info. It handles the UTF-8 encoding / decoding properly. In the PHP script, you can use the built-in base64_decode to decode back to UTF-8. But there’s one caveat using this method: BASE64 encoding contains sometimes the plus (+) sign. This, usually, is transformed into a space in URLs. So when the server gets the AJAX call with a BASE64 encoded parameter containing a +, it can no longer decode it, base64_decode only returns an empty string. This can be worked around:
$result = base64_decode(str_replace(" ","+",$_REQUEST['base64encodedparameter']));
And you have your UTF-8 encoded string in $result.
Also, base64_decode doesn’t care if the trailing = characters get lost on the way, so this method should be safe to use.
There are probably a hundred better way to do this, but I found it working great.
Leave a Reply