Simo Virokannas

Writings and ramblings

Javascript, Base64, PHP, UTF-8

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.


Comments

4 responses to “Javascript, Base64, PHP, UTF-8”

  1. Cagri Canbol

    Thanks bro, that saved zillions of time!

  2. saved the day
    gg

  3. This was REALLY helpful, saved the day…

  4. Yet years later, another appreciative reader. Encoding in javascript and decoding in PHP is exactly what I need to do, and your helpful notes about the + explained everything I was seeing.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.