Encoding common to PHP and Javascript

Hello,

I’d like to encode data in php, create an url containing that data in the querystring, and have a javascript decode it and use it.

Problem: I can’t find a way to encode my data common to PHP and Javascript.

Here’s how my php code looks:


base64_encode(json_encode($someArray));

There is no native base64_decode in javascript.

How should I encode my PHP array to make it url friendly and easily usable by a js script?

Cheers.

:slight_smile:

My question to you would be why are you base64_encoding a JSON array? Not only are you making more work for yourself but your actually making the return data longer and greater in size, it would be much easier if you just stick to using JSON as it will eliminate all the hassles you will need to overcome.

By using the JSON library.

PHP has json_encode() and with JavaScript you can use [url=“https://github.com/douglascrockford/JSON-js”]json2.js from [url=“http://json.org/”]www.json.org with the JSON.parse() command.

Can json encoded data travel through url safely and in a friendly way? If the object/array encoded is big, wouldn’t base_64 reduce the querystring size?

The resulting string is UTF-8 which is as small as a byte or as large as it needs to be to represent the character.

You may want to make good use of urlencode() and [URL=https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/decodeURI]decodeURI() ad well though when using the URL ad a transport medium.

A cheaper way to be used only if the JSON data is trusted, would be:


var obj = eval("(" + jsonStr + ")");

JSON is already JavaScript code. All you have to do is execute it.

Between any client and your own server, such a level of trust can not be guaranteed in any way.
Always use the proper technique of JSON.parse() and you won’t leave yourself open to any issues.

Doesn’t JSON.parse() executed code? I’ve read that json_sans_eval.js was a secure way to deal with JSON data if it can’t be trusted.

To my recollection that was an issue with the original json.js but not with json2.js
Many precautions are taken before using eval on the string. Here is just one set of comments from a part of the process in json2.js that explains what’s going on.


// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.