~ overflow ~

Tag: base64

json decode fails on non utf-8

by z3n on Mar.16, 2010, under Coding, Tips & Hints

Problem:

When sending a non utf-8 string as json, the decoding fails.

Solution:

PHP works as utf-8 as default, since i’m using strings with accents (áéíóú..) those are taken as iso-8859-1. Client-side script will not send as utf-8, not even if you force it, so the best solution is convert the json object’s encoding. You may also want to encode your string as plain chars (I use base64) to avoid issues with IE.

Code would look like this:

$json=json_decode(iconv(‘ISO-8859-1′,’UTF-8′,base64_decode($input)),true);

If you’re working with different charsets just change the iso-8859-1, remember that if you’re working with multibyte chars, such as japanese, chinese, etc, you will need to use the mb functions instead.

Sources:

Pablo Viquez (A solution pretty much like mine but for sending data instead)

2 Comments :, , , , more...

Javascript Base64 -> PHP -> MySQL Issue

by z3n on May.21, 2008, under Tips & Hints

You might be wondering why someone would send encoded data to php to be inserted on a table, just think that you need to put a html into a table, how many issues you can fall into? it’s much easier encode it, so then you fall into a different issue…

i’m using a regular base64 encode/decoder script wich you can find by searching google “javascript base64″;

the problem is that once you send the base64 data to php by POST or GET it gets corrupted! why this happens? cuz life sucks?!

so i figured out a interesting thing

base64 uses the character “+” wich is the same character to determine spaces on the POST/GET data, so basically when you send information by a form it will be sent like this:

“bleh bleh bleh” -> “bleh+bleh+bleh” when php gets it it will convert back to the original string (replacing the “+”’s with ” ” (space)) that made the javascript base64’s encoded information to get corrupted, just like this:

original base64 encode:

PGh0bWw+PGhlYWQ+PHRpdGxlPl

after sending to php it will be added as this on the database:

PGh0bWw PGhlYWQ PHRpdGxlPl

so to fix this issue, you just need a str_replace(" ","+",$base64_data_from_javascript) to fix it.

that’s all.

Leave a Comment :, , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!